Spring Boot全局异常处理的两种方式

1.前后端不分离的项目

public class GlobalExceptionResvoler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        return new ModelAndView("/xxx");
    }
}

2.前后端分离的项目

@ControllerAdvice  //给controller增加一些附加操作
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    //自定义方法 希望这个可以处理所有controller异常
    @ExceptionHandler //用来处理controller异常
    @ResponseBody
    public Map<String, String> exception(Exception exception) {
        log.info("ex: {}", exception.getMessage());
        HashMap<String, String> result = new HashMap<>();
        result.put("msg", exception.getMessage());
        return result;
    }

}

posted @ 2021-10-08 23:41  code-G  阅读(240)  评论(0编辑  收藏  举报