在实际开发中,我们通常根据业务逻辑自定义异常处理,组合 @RestControllerAdvice 和 @ExceptionHandler 注解对异常进行处理,自定义异常通常会包含业务异常和系统异常
示例
- BusinessException.java
public class BusinessException extends RuntimeException { private ResultCode resultCode;
public BusinessException(ResultCode resultCode) { super(resultCode.getMsg()); this.resultCode = resultCode; }
public BusinessException(String message, ResultCode resultCode) { super(message); this.resultCode = resultCode; }
public BusinessException(String message, Throwable cause, ResultCode resultCode) { super(message, cause); this.resultCode = resultCode; }
public ResultCode getResultCode() { return resultCode; }
public void setResultCode(ResultCode resultCode) { this.resultCode = resultCode; } } |
- SystemException.java
public class SystemException extends RuntimeException{ private ResultCode resultCode;
public SystemException(ResultCode resultCode) { super(resultCode.getMsg()); this.resultCode = resultCode; }
public SystemException(String message, ResultCode resultCode) { super(message); this.resultCode = resultCode; }
public SystemException(String message, Throwable cause, ResultCode resultCode) { super(message, cause); this.resultCode = resultCode; }
public ResultCode getResultCode() { return resultCode; }
public void setResultCode(ResultCode resultCode) { this.resultCode = resultCode; } } |
- 通过自定义异常类处理不同场景下的异常情况,我们只需要在全局相应处理类中使用 @ExceptionHandler 注解指定自定义异常的处理方法。同时,允许在异常处理时生成日志和通知等操作。
示例
@Slf4j @RestControllerAdvice public class GlobalExceptionAdvice { @ExceptionHandler(BusinessException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ErrorResult doBusinessException(BusinessException ex) { log.error("业务异常信息 ex={}", ex.getMessage(), ex); return ErrorResult.fail(ex.getResultCode()); }
@ExceptionHandler(SystemException.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ErrorResult doSystemException(SystemException ex) { log.error("系统异常信息 ex={}", ex.getMessage(), ex); //记录日志 //发送特定消息给运维人员,提醒维护 return ErrorResult.fail(ex.getResultCode()); }
@ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ErrorResult doOtherException(Exception ex) { log.error("全局异常信息 ex={}", ex.getMessage(), ex); //记录日志 //发送特定消息给运维人员,提醒维护 return ErrorResult.fail(ResultCode.SYSTEM_ERROR); } |
- 在控制层中处理错误时,只需要手动抛出异常,同时将对应的错误码枚举类传递给异常类,就能实现对异常信息的封装,将错误信息传递到前端
示例
@RestController @RequestMapping("/user") public class UserController{ @GetMapping("/{id}") public User getUserById(@PathVariable Integer id) { User user = userService.getById(id); if (ObjectUtils.isEmpty(user)) { throw new BusinessException(ResultCode.USER_NOT_EXIST); } return user; } }
|
当错误发生时,接口数据返回如下: