展开
拓展 关闭
订阅号推广码
GitHub
视频
公告栏 关闭

错误处理

自定义错误页面

  • 当出现异常时,会根据错误状态码,跳转到相应的页面
  • 例如出现一个404的错误,会首先去找error路径下有没有404错误页面,如果没有则去找有没有4xx的页面,如果也没有,则返回默认的错误信息

处理全局异常

  • @ControllerAdvice+@ExceptionHandler,使用这两个注解处理控制层全局的异常,当控制层出现指定的异常时,执行相应的处理方案
// 这种方式,底层是 ExceptionHandlerExceptionResolver 支持的异常解析器
// 新建异常处理类,当控制层请求出现异常时,跳转到登录页面
@Slf4j
@ControllerAdvice     
public class GlobalExceptionHandler {
	@ExceptionHandler({ArithmeticException.class,NullPointerException.class})     // 该注解表示这是一个异常处理器,参数中指定处理运算异常、空指针异常
	public String handleArithException(Exception e){
		log.error("异常是:{}",e);
		return "login";    // 出现异常时,返回登录页面
	}
}

自定义异常

  • 我们在编写业务时需抛出异常的时候,可抛出一个自定义的异常
// 该方式,底层是 ResponseStatusExceptionResolver的异常解析器
@ResponseStatus(value= HttpStatus.FORBIDDEN,reason = "用户数量太多")
public class UserTooManyException extends RuntimeException {  // 其他业务中可抛出异常 throw new UserTooManyException();

    public  UserTooManyException(){

    }
    public  UserTooManyException(String message){
        super(message);
    }

}

  • 错误状态码查看HttpStatus类
UNAUTHORIZED(401, HttpStatus.Series.CLIENT_ERROR, "Unauthorized"),
PAYMENT_REQUIRED(402, HttpStatus.Series.CLIENT_ERROR, "Payment Required"),
FORBIDDEN(403, HttpStatus.Series.CLIENT_ERROR, "Forbidden"),
NOT_FOUND(404, HttpStatus.Series.CLIENT_ERROR, "Not Found"),
METHOD_NOT_ALLOWED(405, HttpStatus.Series.CLIENT_ERROR, "Method Not Allowed"),
NOT_ACCEPTABLE(406, HttpStatus.Series.CLIENT_ERROR, "Not Acceptable"),
PROXY_AUTHENTICATION_REQUIRED(407, HttpStatus.Series.CLIENT_ERROR, "Proxy Authentication Required"),
REQUEST_TIMEOUT(408, HttpStatus.Series.CLIENT_ERROR, "Request Timeout"),
CONFLICT(409, HttpStatus.Series.CLIENT_ERROR, "Conflict"),
GONE(410, HttpStatus.Series.CLIENT_ERROR, "Gone"),
LENGTH_REQUIRED(411, HttpStatus.Series.CLIENT_ERROR, "Length Required"),
PRECONDITION_FAILED(412, HttpStatus.Series.CLIENT_ERROR, "Precondition Failed"),
PAYLOAD_TOO_LARGE(413, HttpStatus.Series.CLIENT_ERROR, "Payload Too Large"),
// ...

自定义异常解析器

// 自定义一个异常解析器,需实现HandlerExceptionResolver接口
@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(511,"我喜欢的错误");    # 自定义错误状态码和错误msg
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ModelAndView();     # 最后该解析器处理所有异常,并返回错误状态码和错误msg,在精准匹配后,跳转到对应错误页面
    }
}

  • 优先级可以是数字
package org.springframework.core;

public interface Ordered {
    int HIGHEST_PRECEDENCE = -2147483648;
    int LOWEST_PRECEDENCE = 2147483647;

    int getOrder();
}

posted @ 2021-08-09 17:17  DogLeftover  阅读(33)  评论(0编辑  收藏  举报