解决方案:自定义异常类(推荐)
Java标准库中的Exception、RuntimeException等基础异常类都没有提供错误码(code)的属性,因此最常用、最灵活的方式是创建自定义异常类,在其中添加code属性并提供对应的构造方法。
根据业务场景,你可以选择继承受检异常(Exception)或非受检异常(RuntimeException,更推荐用于业务异常,无需强制捕获)。
1. 自定义业务异常类(带错误码)
/** * 自定义业务异常类,支持错误码和错误消息 */publicclassBusinessExceptionextendsRuntimeException{// 错误码privateintcode;// 构造方法1:只传错误消息(默认错误码,比如500)publicBusinessException(Stringmessage){super(message);this.code=500;// 默认系统错误码}// 构造方法2:传错误码和错误消息(核心)publicBusinessException(intcode,Stringmessage){super(message);this.code=code;}// 构造方法3:传错误码、消息和异常原因(用于异常链)publicBusinessException(intcode,Stringmessage,Throwablecause){super(message,cause);this.code=code;}// 获取错误码的getter方法publicintgetCode(){returncode;}}2. 使用自定义异常(指定code)
// 抛出异常:指定错误码(比如401:未授权)和消息thrownewBusinessException(401,"未携带 Token,请登录");3. 捕获异常并获取code
try{// 执行可能抛出异常的逻辑thrownewBusinessException(401,"未携带 Token,请登录");}catch(BusinessExceptione){// 获取错误码和消息intcode=e.getCode();Stringmessage=e.getMessage();System.out.println("错误码:"+code+",错误消息:"+message);}补充:框架自带的异常(适用于特定场景)
如果你使用了Spring、Spring Boot等框架,部分框架提供了支持状态码的异常,但这些主要是HTTP状态码,而非业务错误码:
ResponseStatusException(Spring提供):用于指定HTTP状态码和消息,比如new ResponseStatusException(HttpStatus.UNAUTHORIZED, "未携带 Token,请登录")。HttpClientErrorException:用于HTTP客户端的异常,携带HTTP状态码。