Springboot 自定义异常

当我们使用springboot 写 restful接口时 , 不希望错误信息返回一个Html格式. 例如404时, 返回如图:

i404错误示例

显得非常的不友好 , 接下来, 我们就尝试下自定义异常.

禁用默认异常处理

在配置文件(application.yml)中, 添加如下配置

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

添加全局异常处理控制器

package club.maoyupeng.scm.base.web.controller;

import club.maoyupeng.utils.result.ResponseModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;


/**
 * <b>标题:    </b><br />
 * <pre>
 * </pre>
 *
 * @author 毛宇鹏
 * @date 创建于 下午1:56 2018/9/27
 */
@ControllerAdvice
public class ErrorController  {
    protected final ResultUtil result = new ResultUtil();

    private static final Logger log = LogManager.getLogger(ErrorController.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseModel systemException(Exception e) {
        log.error("System error");
        return result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseModel methodNotSupported(NoHandlerFoundException e) {
        log.error("method not found : 404");
        return result.error(HttpStatus.NOT_FOUND.value(), e.getMessage());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public ResponseModel methodNotSupported(HttpRequestMethodNotSupportedException e) {
        log.error("method not support : 405");
        return result.error(HttpStatus.METHOD_NOT_ALLOWED.value(), e.getMessage());
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public ResponseModel mediaTypeNotSupported(HttpMediaTypeNotSupportedException e) {
        log.error("media type not support : 415");
        return result.error(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), e.getMessage());
    }

    @ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    public ResponseModel mediaTypeNotAcceptable(HttpMediaTypeNotAcceptableException e) {
        log.error("media type not acceptable : 406");
        return result.error(HttpStatus.NOT_ACCEPTABLE.value(), e.getMessage());
    }
}

ResultUtil 参考代码:
主要是将错误码和错误信息封装成一个json对象, 例如: {code: 400, msg: '错误信息'}

public ResponseModel error(int errorCode, String message) {
    ResponseModel model = new ResponseModel();
    super.setErrorMessage(model, errorCode, message);
    return model;
}

结果

改造前
i改造后
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容