SpringBoot - 异常处理

异常处理

  1. 默认规则:
    • 默认情况下,Spring Boot提供/error处理所有错误的映射
    • 对于机器客户端,它将生成JSON响应,其中包含错误,HTTP状态和异常消息的详细信息。对于浏览器客户端,响应一个“ whitelabel”错误视图,以HTML格式呈现相同的数据
      • 机器客户端(Postman):
        在这里插入图片描述
        - 浏览器客户端: 在这里插入图片描述
  2. 自定义错误页面:
    • 直接将404.html和5xx.html页面放在resoures/static/error/文件夹下面
      在这里插入图片描述
    • 自定义异常处理:
      @Configuration
      public class WebException implements HandlerExceptionResolver {
              
              
          @Override
          public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
              
              
              ModelAndView mv = new ModelAndView();
              if (e instanceof NullPointerException) {
              
              
                  mv.setViewName("5xx");
              } else if (e instanceof ArithmeticException) {
              
              
                  mv.setViewName("404");
              }
              mv.addObject("error", e.toString());
              return mv;
          }
      }
      
      更多自定义异常处理:转自:https://blog.csdn.net/ko289830707/article/details/85244580

猜你喜欢

转载自blog.csdn.net/weixin_43985446/article/details/113954163
今日推荐