SpringBoot响应自定义异常消息并且自动识别客户端与浏览器做出不同响应

SpringBoot响应自定义异常消息并且自动识别客户端与浏览器做出不同响应

使用 @ControllerAdvice 注解和 @ExceptionHandler 注解将异常捕获后直接返回数据。(这时候是没有自适应效果,浏览器还是客户端请求错误都是返回JSON形式数据)
@ControllerAdvice
public class MyExceptionHandler {

    // 浏览器客户端返回的都是json
    @ResponseBody
    @ExceptionHandler(UserNotExistException.class)
    public Map<String,Object> handleException(Exception e){
        Map<String,Object> map = new HashMap<>();
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        return map;
    }
捕获异常后将转发到 /error ,SpringBoot会使用BasicErrorController来接管错误请求然后去响应,这时候已经是自适应的错误响应。
 		@ExceptionHandler(UserNotExistException.class)
    public String handleException(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //传入我们自己的错误状态码  4xx 5xx,否则就不会进入定制错误页面的解析流程,就只会返回默认的错误页面
        /**
         * Integer statusCode = (Integer) request
         .getAttribute("javax.servlet.error.status_code");
         */
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        //转发到/error
        return "forward:/error";
    }
将自己定制的数据携带出去

因为返回的数据中都是通过BasicErrorAttributes.getErrorAttributes方法来获取model数据,这个方法是DefaultErrorAttribute中的方法。所以想要返回自定义的数据直接手写DefaultErrorAttribute类即可。

  @RequestMapping(produces = "text/html")
  public ModelAndView errorHtml(HttpServletRequest request,
        HttpServletResponse response) {
     HttpStatus status = getStatus(request);
     Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
           request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
     response.setStatus(status.value());
     ModelAndView modelAndView = resolveErrorView(request, response, status, model);
     return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
  }

ErrorMvcAutoConfigration中默认会注入DefaultErrorAttributes,如果自己手写一个ErrorAttributes(这是一个接口)然后放入容器中则可以让SpringBoot在获取model数据时从自定义的ErrorAttributes中获取

  @Bean
  @ConditionalOnMissingBean(value = ErrorAttributes.class, search = SearchStrategy.CURRENT)
  public DefaultErrorAttributes errorAttributes() {
     return new DefaultErrorAttributes();
  }
  //给容器中加入我们自己定义的ErrorAttributes
  @Component
  public class MyErrorAttributes extends DefaultErrorAttributes {

      //返回值的map就是页面和json能获取的所有字段
      @Override
      public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
          Map<String, Object> map = super.getErrorAttributes(requestAttributes, includeStackTrace);
          map.put("company","atguigu");

          //我们的异常处理器携带的数据
          Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
          map.put("ext",ext);
          return map;
      }

  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值