SpingBoot三:统一返回类与错误处理器ExceptionHandler

8 篇文章 0 订阅

在上一个介绍中,Controlle层我们返回的数据类型各不一致,如果出现错误的话,还会返回一个错误页面,这对请求很不友好,所以我们对返回结果做一个统一的包装。

首先定义一个简单的错误码及错误信息的枚举类:ResponseCodeConstant。

public enum ResponseCodeConstant {
    SUCCESS(200, "接口调用成功"),
    FAIL(300, "业务处理失败"),
    PARAM_INPUT_INVALID(400, "参数校验非法"),
    PARAM_ABNORMAL(401, "参数异常"),
    UNKNOW_SYSTEM_ERROR(500, "未知系统异常"),
    TIMEOUT(501, "后端接口调用超时");


    private int code;
    private String message;

    ResponseCodeConstant(int code, String message) {
        this.code = code;
        this.message = message;
    }


    public String toString() {
        return "Code: " + this.code + ";Messge: " + this.message;
    }

    public int getCode() {
        return this.code;
    }

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

    public String getMessage() {
        return this.message;
    }

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

自定义一个统一返回的基础类:BaseResult。

public class BaseResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private int code;
    private String msg;
    private T data;

    public static <T> BaseResult<T> success(T t) {
        BaseResult<T> rst = new BaseResult<>();
        rst.setCode(ResponseCodeConstant.SUCCESS.getCode());
        rst.setData(t);
        return rst;
    }

    public static <T> BaseResult<T> fail(ResponseCodeConstant responseCodeConstants) {
        return fail(responseCodeConstants, null);
    }

    public static <T> BaseResult<T> fail(String msg) {
        BaseResult<T> rst = new BaseResult<>();
        rst.setMsg(msg);
        rst.setCode(ResponseCodeConstant.FAIL.getCode());
        return rst;
    }

    public static <T> BaseResult<T> fail(ResponseCodeConstant responseCodeConstant, String msg) {
        BaseResult<T> rst = new BaseResult<>();
        if (StringUtils.isNotBlank(msg)) {
            rst.setMsg(msg);
        } else {
            rst.setMsg(responseCodeConstant.getMessage());
        }
        rst.setCode(responseCodeConstant.getCode());
        return rst;
    }

    public static <T> BaseResult<T> fail(int code, String msg) {
        BaseResult<T> rst = new BaseResult<>();
        rst.setMsg(msg);
        rst.setCode(code);
        return rst;
    }

    public boolean isSuccess(){
        return this.code == ResponseCodeConstant.SUCCESS.getCode();
    }


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

    public int getCode() {
        return this.code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return this.msg;
    }

    public T getData() {
        return this.data;
    }

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

定义一个错误类:BaseException

public class BaseException extends RuntimeException {

    private int errCode;

    public int getErrCode() {
        return errCode;
    }

    public void setErrCode(int errCode) {
        this.errCode = errCode;
    }

    private BaseException() {
        super();
    }

    public BaseException(String message) {
        super(message);
        this.errCode = ResponseCodeConstant.FAIL.getCode();
    }


    public BaseException(int errorCode, String message) {
        super(message);
        this.errCode = errorCode;
    }
}

接下来就是重点了,统一的异常捕获处理类:ExceptionsHandler

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @Author fusheng
 */
//处理全局异常
@RestControllerAdvice
@ResponseBody
public class ExceptionsHandler {

    @ExceptionHandler(NullPointerException.class)
    public BaseResult handleNPException(NullPointerException np) {
        return BaseResult.fail(ResponseCodeConstant.PARAM_ABNORMAL, "参数空异常");
    }

    @ExceptionHandler(IndexOutOfBoundsException.class)
    public BaseResult handleIndexException(IndexOutOfBoundsException e) {
        return BaseResult.fail(ResponseCodeConstant.PARAM_ABNORMAL, "选取长度过长=" + e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public BaseResult handleBindException(BindException e) {
        String msg = e.getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));
        return BaseResult.fail(ResponseCodeConstant.PARAM_INPUT_INVALID, msg);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResult handleParamException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));
        return BaseResult.fail(ResponseCodeConstant.PARAM_INPUT_INVALID, message);
    }

    @ExceptionHandler(BaseException.class)
    public BaseResult handleBaseException(BaseException e) {
        return BaseResult.fail(e.getErrCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResult handleException(Exception e){
        return BaseResult.fail(e.getMessage());
    }

}
@RestControllerAdvice相当于@ControllerAdvice+@ResponseBody注解,用来捕获项目的全局异常,并返回。
@ExceptionHandler用来指定要捕获的异常,可以是多个。@ExceptionHandler({NullPointerException.class,IllegalArgumentException.class})

虽然上面的例子中捕获NP和越界异常,但在实际开发中要尽量避免抛出这种异常,要对可能为null的数据进行判断,截取数组,集合或者字符串的时候要根据长度做一下控制。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中,我们可以使用统一返回处理来规范 API 接口的返回格式,避免重复的代码和降低维护成本。 一般来说,我们可以定义一个 Result 来封装接口返回的数据,包括状态码、提示信息和返回数据等。同时,我们还可以定义一个异常处理来捕获全局的异常,并将异常信息封装到 Result 返回给前端。 以下是一个示例代码: ```java @Data @NoArgsConstructor @AllArgsConstructor public class Result<T> { private Integer code; private String msg; private T data; public static <T> Result<T> success(T data) { return new Result<>(200, "success", data); } public static Result<?> error(Integer code, String msg) { return new Result<>(code, msg, null); } } @ControllerAdvice @ResponseBody public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public Result<?> handleException(Exception e) { log.error("未知异常:{}", e.getMessage()); return Result.error(500, "服务器内部错误"); } @ExceptionHandler(value = BusinessException.class) public Result<?> handleBusinessException(BusinessException e) { log.error("业务异常:{}", e.getMessage()); return Result.error(e.getCode(), e.getMessage()); } } ``` 在上面的代码中,我们定义了一个 Result 来封装接口返回的数据。其中,success 方法表示成功时返回的结果,error 方法表示失败时返回的结果。 同时,我们还定义了一个全局异常处理器 GlobalExceptionHandler,用来捕获全局的异常。在 handleException 和 handleBusinessException 方法中,我们分别处理了未知异常和业务异常,并将异常信息封装到 Result 返回给前端。 通过使用统一返回处理,我们可以大大简化接口返回的代码,提高代码的可维护性和可读性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值