Spring Boot unified Exception Management

Foreword

Often there will be various exceptions, how to deal with these unified treatment of these anomalies has become a problem, Spring Boot supports a variety of exception handling mechanisms, today we have a brief look at common unified exception handling mechanism in the daily development.

@ControllerAdvicethe way

By using @ControllerAdviceand @ExceptionHandlerdefine a uniform exception handling class, rather than individually defined in each Controller.

HTML abnormal
Define consistent exception handling controller
@ControllerAdvice
class GlobalExceptionHandler {

    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", e);
        mav.addObject("url", req.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }
}
复制代码
Define consistent exception handling page
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title>统一异常处理</title>
</head>
<body>
    <h1>Error Handler</h1>
    <div th:text="${url}"></div>
    <div th:text="${exception.message}"></div>
</body>
</html>
复制代码
JSON abnormal
Harmonization of definitions of abnormal response JSON
@Data
public class ErrorResult<T> {
	private Integer code;
    private String message;
    private String url;
    private T data;
}
复制代码
Define consistent exception handling controller
@ControllerAdvice
public class GlobalExceptionHandler {
    //捕获自定义业务异常
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ErrorResult<Object> jsonErrorHandler(HttpServletRequest req,BizException e) throws Exception {
        ErrorResult<Object> r = new ErrorResult<>();
        r.setMessage(e.getMessage());
        r.setCode(ErrorInfo.ERROR);
        r.setUrl(req.getRequestURL().toString());
        return r;
    }
}
复制代码

2. BasicErrorControllerway

With this scheme, the interface if the request is without own HTMLorRESTful API

Defined exception handler uniform
@Controller
@RequestMapping("/error")
public class GlobalErrorController extends BasicErrorController {

    @Autowired
    public GlobalErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
        super(errorAttributes, serverProperties.getError());
    }

    @RequestMapping(produces = "text/html")
    @Override
    public ModelAndView errorHtml(HttpServletRequest request,
                                  HttpServletResponse response) {
        return super.errorHtml(request, response);
    }

    @RequestMapping
    @ResponseBody
    @Override
    @SuppressWarnings("unchecked")
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        Map<String, Object> body = super.getErrorAttributes(request,
                isIncludeStackTrace(request, MediaType.ALL));

        String message = body.get("message") != null ? (String) body.get("message") : null;
        Integer statusCode = body.get("status") != null ? (Integer) body.get("status") : null;

        Object exception = body.get("exception");
        if (exception instanceof TradeBizException) {
            TradeBizException bre = (TradeBizException) exception;
            statusCode = bre.getCode();
        }

        Wrapper<Object> wrap = WrapMapper.wrap(statusCode == 0 ? Wrapper.ERROR_CODE : statusCode, message);
        Map res = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            String s = mapper.writeValueAsString(wrap);
            res = mapper.readValue(s, Map.class);
        } catch (IOException e) {
            e.printStackTrace();
        }

        HttpStatus status = super.getStatus(request);
        return new ResponseEntity<Map<String, Object>>(res, status);
    }
}
复制代码

Reference article

Unified Exception Management

Spring Boot unified exception handling in Web applications

Guess you like

Origin juejin.im/post/5e5b851af265da570e39a6e7