Spring Boot全局异常处理

/ Spring Boot / 没有评论 / 43浏览

Spring Boot全局异常处理。

描述

在代码中抛出业务异常,统一进行异常处理,返回约定的json格式。

{
    "code": 业务错误码/成功,
    "message": 业务错误描述/成功描述,
    "data": 返回的数据
}

这里我的http status一直返回200,通过code来区分异常。

通常,通过http status区分请求异常(400、401),code来区分业务异常。

设计

业务异常定义

public class BizException extends RuntimeException {

    private int code;
    private String message;

    public BizException(int code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }

    public BizException(int code, String message, Throwable throwable) {
        super(message, throwable);
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    @Override
    public String getMessage() {
        return message;
    }
}

抛出业务异常

@Controller
public class ExampleController {

    @RequestMapping("/")
    public String index() {
        throw new BizException(1001, "error");
    }

}

定义返回类型

public class Result<T> {

    private int code;
    private String message;
    private T data;

    private Result() {
    }

    private Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> Result<T> ok(T data) {
        return new Result<>(HttpStatus.OK.value(), null, data);
    }

    public static <T> Result<T> ok(String message, T data) {
        return new Result<>(HttpStatus.OK.value(), message, data);
    }

    public static Result<Void> fail(String message) {
        return new Result<>(HttpStatus.INTERNAL_SERVER_ERROR.value(), message, null);
    }

    public static Result<Void> fail(int code, String message) {
        return new Result<>(code, message, null);
    }

    public static <T> Result<T> fail(int code, String message, T data) {
        return new Result<>(code, message, data);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

全局异常处理

@RestControllerAdvice
public class RestExceptionHandler {

    private static final Logger LOG = LoggerFactory.getLogger(RestExceptionHandler.class);

    @ExceptionHandler(BizException.class)
    public Result<?> handleBizException(BizException e) {
        LOG.error("[全局异常返回处理]", e);
        int code = e.getCode();
        String message = e.getMessage();
        return Result.fail(code, message);
    }

    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        LOG.error("[全局异常返回处理]", e);
        String message = e.getMessage();
        return Result.fail(message);
    }

}

结果