spring boot异常处理
错误来源:
对于其他的url访问错误,资源找不到,报404
服务器内部异常,报5XX
异常处理方法
方法一、自定义错误页
在error/404.html、error/4xx.html、error/5xx.html;有精确的错误状态码页面就匹配精确,没有就找 4xx.html、5xx.html;
如果都没有就触发spring boot自带的Whitelabel Error Page异常页面
对于机器客户端,它将生成JSON响应,其中包含错误,HTTP状态和异常消息的详细信息。对于浏览器客户端,响应一个“ whitelabel”错误视图,以HTML格式呈现相同的数据
可以将错误消息在自定义错误页显示出来
error/4xx.html 错误页:
4XX报错
<h1>状态码:[[${status}]]</h1>
时间:[[${timestamp}]]
<h2>消息:[[${message}]]</h2>
<h3>错误:[[${error}]]</h3>
<h3>查出:[[${trace}]]</h3>
方法二、@ControllerAdvice+@ExceptionHandler处理全局异常
创建异常处理类,捕获异常
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandle {
@ExceptionHandler({ArithmeticException.class,NullPointerException.class}) //捕获异常,异常处理
public String handleArithException(Exception e){
log.error("异常:{}",e); //控制台打印异常
return "error/404"; //视图地址,捕获异常后跳转的页面,也可跳转到登录页面等
}
}
异常处理类能捕获的异常则自己处理,异常处理类不能处理的异常交给 方法一自定义错误页
方法三、@ResponseStatus+自定义异常 ;底层是 ResponseStatusExceptionResolver ,把responseStatus注解的信息底层调用 response.sendError(statusCode, resolvedReason),tomcat发送的/error
自定义异常
@ResponseStatus(value= HttpStatus.FORBIDDEN,reason = "用户数量太多") //message:用户数量太多
public class UserTooManyException extends RuntimeException {
public UserTooManyException(){
}
public UserTooManyException(String message){
super(message);
}
}
控制器内部 抛出异常
@GetMapping("/editable_table")
public String editable_table(HttpServletRequest servletRequest){
List<User> users = Arrays.asList(new User("张飞", "111"),new User("刘备", "1590"),new User("关羽", "motuochr"));
if(users.size()>2){
throw new UserTooManyException();//抛出自定义异常
}
servletRequest.setAttribute("users",users);
return "table/editable_table";
}
方法四、自定义实现 HandlerExceptionResolver 处理异常;可以作为默认的全局异常处理规则(处理异常解析器,不能处理访问错误)
处理所有异常,不能处理错误的 url 映射
@Order(value= Ordered.HIGHEST_PRECEDENCE) //优先级,数字越小优先级越高
@Component
public class CustomerHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response,
Object handler, Exception ex) {
try {
response.sendError(522,"自定义的错误"); //所有异常的 status:522,message:自定义的错误
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView();
}
}
HandlerExceptionResolver缺点:
HandlerExceptionResolver对异常的处理需要手动判断,并且所有的错误都在一个方法中处理,耦合度太大
优先级高(@Order(value= Ordered.HIGHEST_PRECEDENCE) //优先级,数字越小优先级越高),直接覆盖方法二和方法三,不覆盖方法一 404