自定义错误页
-
error/404.html error/5xx.html;有精确的错误状态码页面就匹配精确,没有就找4xx.html,如果都没有就触发白页
-
@ControllerAdvice + @ExceptionHandler处理异常:底层是ExceptionHandlerExceptionResolver支持的
/**
* 处理整个web controller 的异常
*/
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler({ArithmeticException.class,NullPointerException.class}) //处理异常
public String handlerArithException(Exception e){
log.info("异常是: {}",e);
return "up"; //视图地址
}
}
- @ResponseStatus+自定义异常,底层是ResponseStatusExceptionResolver,把responsestatus注解的信息组装成ModelAndView返回,底层调用response.sendError(statusCode, resolvedReason);其实就是tomcat发送的/error
/**
* 自定义异常处理
*/
@ResponseStatus(value = HttpStatus.FORBIDDEN,reason = "用户数量太多")
public class UserTooManyException extends RuntimeException{
public UserTooManyException(){
}
public UserTooManyException(String message){
super(message);
}
}
- Spring底层的异常,如参数类型转换异常;DefaultHandlerExceptionResolver处理框架底层的异常。 response.sendError(HttpServletResponse.SC_BAD_REQUEST,ex.getMessage());
自定义实现HandlerExceptionResolver处理异常,可以作为默认的全局异常处理规则
@Order(value = Ordered.HIGHEST_PRECEDENCE) //优先级,数字越小优先级越高,给自定义的异常提高优先级,优先进入自定义的异常处理
@Component
public class CustomerHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
try {
httpServletResponse.sendError(511,"一个异常");
}catch (IOException exception){
exception.printStackTrace();
}
return new ModelAndView();
}
}
- ErrorViewResolver实现自定义处理异常
- response.sendError,error请求就会转给controller
- 你的异常没有任何人能处理,交给tomcat底层response.sendError,error请求就会转给controller
- basicErrorController要去的页面地址是ErrorViewResolver解析,所有的异常都会被他捕获