springboot rest接口404和500的特殊处理

 

首先添加全局异常处理:

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @ExceptionHandler({BaseException.class, HttpMessageNotReadableException.class, HttpMediaTypeNotSupportedException.class, MaxUploadSizeExceededException.class, HttpRequestMethodNotSupportedException.class, MethodArgumentNotValidException.class, BindException.class,})
    Object serverExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        MsgCode msgCode;
        BaseException baseException = null;
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        Response result;
        if (e instanceof BaseException) {
            baseException = (BaseException) e;
            msgCode = baseException.getMsgCode();
            result = ResponseUtil.fail(Collections.EMPTY_MAP, msgCode, baseException.getMessage());
        } else if (e instanceof HttpMessageNotReadableException) {
            result = ResponseUtil.fail(Collections.EMPTY_MAP, "缺少必须的参数");
        } else if (e instanceof HttpMediaTypeNotSupportedException) {
            result = ResponseUtil.fail(Collections.EMPTY_MAP, "请求类型不匹配");
        } else if (e instanceof MaxUploadSizeExceededException) {
            result = ResponseUtil.fail(Collections.EMPTY_MAP, "请不要上传超过10MB的文件");
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            result = ResponseUtil.fail(Collections.EMPTY_MAP, "不支持该类型的请求");
        } else if (e instanceof MethodArgumentNotValidException) {
            result = ResponseUtil.fail(Collections.EMPTY_MAP, ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage());
        } else if (e instanceof BindException) {
            result = ResponseUtil.fail(Collections.EMPTY_MAP, ((BindException) e).getBindingResult().getFieldError().getDefaultMessage());
        } else {
            result = ResponseUtil.fail(Collections.EMPTY_MAP, CommonCode.OPER_BASE_FAILD);
        }
        log.error("异常信息:{}", Optional.ofNullable(baseException).filter(e1 -> e1.getMsgCode() != null).map(b -> b.getMsgCode().getMessage()).orElse(e.getMessage()));
        e.printStackTrace();
        try (PrintWriter printWriter = response.getWriter()) {
            printWriter.write(OBJECT_MAPPER.writeValueAsString(result));
        } catch (IOException e1) {
        }
        return null;
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object defaultErrorHandler(Exception e) {
        if (e instanceof NoHandlerFoundException) {
            return ResponseUtil.fail(Collections.EMPTY_MAP, CommonCode.OPER_NOTFOUND);
        } else {
            return ResponseUtil.fail(Collections.EMPTY_MAP, CommonCode.OPER_BASE_FAILD);
        }
    }

在application.yml中添加以下配置来告诉springboot不要建默认的资源映射

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

 =============================================================================================上面这个方案是可以,但是很多时候我们项目中都会用swagger来自动帮我们生成文档,如果按照那个方案的话,你会发现swagger失效。这里我贴出我的终极解决方案

只需要在你的拦截器里面添加这个代码就行:


        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code");
        if (statusCode != null) {
            switch (statusCode) {
                case 404:
                    throw new NoHandlerFoundException(request.getMethod(),request.getRequestURI(),HttpHeaders.EMPTY);
                case 500:
                    throw new Exception("");

            }
        }

 

转载于:https://my.oschina.net/kkrgwbj/blog/2967023

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值