likes
comments
collection
share

SpringBoot的全局异常像诗一样优雅

作者站长头像
站长
· 阅读数 3

前言

在Spring Boot应用中,全局异常的处理是一个非常重要的方面,它可以提高系统的稳定性和用户体验。在这篇博客中,我们将介绍如何在Spring Boot中进行全局异常的封装和统一处理。

全局异常处理能够捕获应用中所有未处理的异常,统一进行处理,防止异常信息泄露到客户端,同时也能够记录异常信息以便后续的调试和分析。

接下来就用SpringBoot实例代码实现一个简单的全局异常拦截。

创建全局异常类

首先,我们需要创建一个自定义的全局异常类,继承自RuntimeException,用于封装业务异常信息。

/**
可直接进行throw该异常类进行返回信息
**/
public class CustomException extends RuntimeException {
    //错误码枚举
    private final ErrorCode errorCode;

    public CustomException(ErrorCode errorCode) {
        super(errorCode.getMessage());
        this.errorCode = errorCode;
    }

    public ErrorCode getErrorCode() {
        return errorCode;
    }
}

创建错误码枚举

为了更好地封装异常信息,我们创建一个错误码的枚举类,用于定义异常码和异常信息。

public enum ErrorCode {
    SUCCESS("10000", "success"),
    SYSTEM_ERROR("500", "系统系统,请联系管理员"),
    NOT_FOUNT("404","未找到对应的资源");

    // 其他错误码...

    private final String code;
    private final String message;

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

    public String getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

创建全局异常处理器

然后,我们创建一个全局异常处理器,使用@ControllerAdvice注解,配合@ExceptionHandler注解处理各种异常。

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<Response> handleCustomException(CustomException ex) {
        ErrorCode errorCode = ex.getErrorCode();
        return new ResponseEntity<>(Response.error(errorCode.getCode(), errorCode.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Response> handleOtherExceptions(Exception ex) {
        return new ResponseEntity<>(Response.error(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

创建错误响应类

最后,我们创建一个错误响应类,用于返回统一的错误格式。

@Data
public class Response<T> {
    private  String code;
    private  String message;
    private T data;
    //默认的返回成功
    public static Response success(){
        Response response  =new Response();
        response.setCode(ErrorCode.SUCCESS.getCode());
        response.setMessage(ErrorCode.SUCCESS.getMessage());
        return response;
    }
    //带内容的返回成功
    public static <T> Response success(T data){
        Response<T> response  =new Response<T>();
        response.setCode(ErrorCode.SUCCESS.getCode());
        response.setData(data);
        response.setMessage(ErrorCode.SUCCESS.getMessage());
        return response;
    }
    //默认的返回失败
    public static Response error(){
        Response response  =new Response();
        response.setCode(ErrorCode.SYSTEM_ERROR.getCode());
        response.setMessage(ErrorCode.SYSTEM_ERROR.getMessage());
        return response;
    }
    //自定义的返回失败
    public static Response error(String code,String msg){
        Response response  =new Response();
        response.setCode(code);
        response.setMessage(msg);
        return response;
    }
}

测试

现在,我们可以在业务代码中通过抛出CustomException来触发全局异常处理,例如:

@RestController
@RequestMapping("/api/test")
public class TestConroller {
    @GetMapping("/success")
    public ResponseEntity<Response> successObj(){
        return ResponseEntity.ok(Response.success("111111"));
    }
    @GetMapping("/error")
    public ResponseEntity<Response> error(String name) {
    //传入的name等于张三时,抛出我们的异常处理。
        if(StringUtils.equals(name,"zhangsan")){
            throw new CustomException(ErrorCode.SYSTEM_ERROR);
        }
        return ResponseEntity.ok(Response.success());
    }
}    

访问:/api/test/success 返回:

{
"code": "10000",
"message": "success",
"data": "111111"
}

访问:/api/test/error?name=zhangsan 返回:

{
"code": "500",
"message": "系统系统,请联系管理员",
"data": null
}

通过以上步骤,我们成功地封装了全局异常并进行了统一处理。这种方式不仅提高了代码的可维护性,还使得异常信息的格式更加一致,方便客户端或其他系统进行处理。全局异常处理是一个非常值得关注的话题,尤其是在构建健壮的后端应用时。