自定义BusinessException
时间: 2024-01-16 19:02:30 浏览: 25
自定义 `BusinessException` 可以让我们更好地处理业务逻辑相关的异常,以下是一个简单的示例:
```java
public class BusinessException extends RuntimeException {
private int code;
private String message;
public BusinessException(int code, String message) {
super(message);
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
```
使用时,可以在业务逻辑中抛出 `BusinessException`,如:
```java
public class UserService {
public void createUser(User user) {
if (user.getName() == null || user.getName().isEmpty()) {
throw new BusinessException(1001, "用户名不能为空");
}
// ...
}
}
```
在全局异常处理器中,可以针对 `BusinessException` 进行特殊处理,如返回自定义的错误信息和状态码:
```java
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<?> handleBusinessException(BusinessException ex) {
Map<String, Object> error = new HashMap<>();
error.put("code", ex.getCode());
error.put("message", ex.getMessage());
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(error);
}
}
```