不积跬步,无以至千里;不积小流,无以成江海。大家好,我是闲鹤,公众号:xxh_zone,十多年开发、架构经验,先后在华为、迅雷服役过,也在高校从事教学3年;目前已创业了7年多,主要从事物联网/车联网相关领域和业务。喜欢交友、骑行、写毛笔字、弹吉他、折腾硬件和写代码。
导读
这是一系列关于 SpringBoot Web框架实战 的教程,从项目的创建,到一个完整的 web 框架(包括异常处理、拦截器、context 上下文等);从0开始,到一个可以直接运用在生产环境中的web框架,所有源码均开源。
正文
访问 SpringBoot server 时,当内部出现异常的话,SpringBoot 有一套自己的异常处理,同时向页面输出相关内容。
比如,当我们访问一个不存在的路由时,Spring Boot 默认会返回:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Oct 14 16:51:35 CST 2022
There was an unexpected error (type=Not Found, status=404).
出于各种考量,当 server 出现异常时,我们希望是输出我们自定义的内容,此时我们只需要创建我们自己的异常处理。
1. 新建类
package org.example.controller;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class DefExceptionHandle {
@ExceptionHandler(value = RuntimeException.class)
@ResponseBody
public String exceptionHandler(HttpServletRequest req, RuntimeException e) {
return "运行时异常: " + e.getMessage();
}
/**
* 处理空指针