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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章