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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

 

首先添加全局异常处理:

@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

你可能感兴趣的:(springboot rest接口404和500的特殊处理)