返回

自定义SpringBoot错误码:让异常处理更优雅

后端

自定义 Spring Boot 错误码:打造更友好、更人性化的异常处理

一、定制错误码的必要性

Spring Boot 中的默认异常信息往往晦涩难懂,难以排查问题。自定义错误码可以让错误信息更清晰易懂,便于开发人员迅速定位和解决问题。

二、自定义错误码的步骤

  1. 创建自定义异常类 :继承自 ExceptionRuntimeException,定义错误码和错误信息。
public class CustomException extends RuntimeException {

    private Integer errorCode;
    private String errorMessage;

    // 构造函数,设置错误码和错误信息
    public CustomException(Integer errorCode, String errorMessage) {
        super(errorMessage);
        this.errorCode = errorCode;
        this.errorMessage = errorMessage;
    }

    // getter 和 setter 方法,方便访问和修改错误码和错误信息
    public Integer getErrorCode() { return errorCode; }
    public String getErrorMessage() { return errorMessage; }

}
  1. 在服务端抛出自定义异常 :发生错误时,抛出自定义异常,指定错误码和错误信息。
// 用户控制器
@RestController
public class UserController {

    @GetMapping("/api/user/{id}")
    public User getUserById(@PathVariable Long id) {
        if (id == null || id <= 0) {
            throw new CustomException(400, "用户ID不能为空或小于等于0");
        }
        // 省略其他代码
    }

}
  1. 在控制器中捕获异常并返回错误信息 :使用 @ExceptionHandler 注解捕获自定义异常,返回错误信息。
// 用户控制器
@RestController
public class UserController {

    @GetMapping("/api/user/{id}")
    public User getUserById(@PathVariable Long id) {
        try {
            // 省略其他代码
        } catch (CustomException e) {
            return new ResponseEntity<>(e.getErrorMessage(), HttpStatus.BAD_REQUEST);
        }
    }

}

三、支持国际化

为支持国际化,在 resources 目录下创建 messages.properties 文件,定义错误信息的国际化资源:

error.400=用户ID不能为空或小于等于0
error.404=用户不存在

在控制器中使用 @MessageSource 注解获取国际化资源:

// 用户控制器
@RestController
public class UserController {

    @Autowired
    private MessageSource messageSource;

    @GetMapping("/api/user/{id}")
    public User getUserById(@PathVariable Long id) {
        try {
            // 省略其他代码
        } catch (CustomException e) {
            String errorMessage = messageSource.getMessage("error." + e.getErrorCode(), null, LocaleContextHolder.getLocale());
            return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
        }
    }

}

四、总结

通过自定义错误码和支持国际化,Spring Boot 的异常处理更加人性化和高效。开发人员可以轻松理解错误信息,缩短问题定位和解决时间。

常见问题解答

  1. 为什么需要自定义错误码?
    答:默认错误信息晦涩难懂,自定义错误码能让错误信息更清晰易懂。

  2. 如何创建自定义异常类?
    答:继承 ExceptionRuntimeException,并定义错误码和错误信息。

  3. 如何抛出自定义异常?
    答:发生错误时,使用自定义异常类抛出异常。

  4. 如何捕获自定义异常?
    答:使用 @ExceptionHandler 注解在控制器中捕获异常。

  5. 如何支持国际化?
    答:创建 messages.properties 文件,并使用 @MessageSource 注解获取国际化资源。