SpringBoot 全局异常

@RestControllerAdvice
public class ApiExceptionHandler {

    private static Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);

    // 对表单验证时抛出的 MethodArgumentNotValidException 异常做统一处理
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> validException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> errors = bindingResult.getAllErrors();
        if (!errors.isEmpty()) {
            // 只显示第一个错误信息
            ErrorBody body = new ErrorBody(HttpStatus.BAD_REQUEST.value(), errors.get(0).getDefaultMessage());
            return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>("valid error", HttpStatus.BAD_REQUEST);
    }

    // 业务异常的默认处理方式
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<?> businessException(BusinessException e) {
        ErrorBody body = new ErrorBody(e.getCode(), e.getMessage());
        return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }

    // 代码异常的处理方式
    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> defaultHandler(Exception e) {
        log.error(e.getMessage(), e);
        ErrorBody body = new ErrorBody(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
        return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

ErrorBody

public class ErrorBody {
    private Integer code;
    private String message;
    private long timestamp = System.currentTimeMillis();

    public ErrorBody(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }
}

BusinessException

public class BusinessException extends RuntimeException {

    private Integer code;

    public BusinessException(Integer code) {
        this.code = code;
    }

    public BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

 

在Spring Boot中,可以通过定义全局异常来处理应用程序中的异常情况。以下是一种常见的处理方法: 1. 创建一个全局异常处理类,可以命名为 `GlobalExceptionHandler`。 ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception ex) { // 处理异常,并返回合适的响应 return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Internal Server Error"); } // 可以添加其他异常处理方法,比如处理特定类型的异常 // @ExceptionHandler(YourCustomException.class) // public ResponseEntity<String> handleYourCustomException(YourCustomException ex) { // // 处理自定义异常,并返回合适的响应 // return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage()); // } } ``` 2. 在 `GlobalExceptionHandler` 类上使用 `@ControllerAdvice` 注解,表示它是一个全局异常处理类。 3. 在 `GlobalExceptionHandler` 类中,使用 `@ExceptionHandler` 注解来指定要处理的异常类型,比如 `Exception.class` 表示处理所有异常。 4. 在异常处理方法中,可以根据实际情况进行异常处理,并返回合适的响应。在上述示例中,我们处理了 `Exception` 类型的异常,并返回了一个表示内部服务器错误的响应。 5. 可以根据需要添加其他异常处理方法,比如处理特定类型的自定义异常。在处理自定义异常时,可以根据具体的业务逻辑进行异常处理,并返回相应的响应。 通过以上步骤,我们可以实现全局异常处理,统一处理应用程序中的异常情况。这样可以使代码更加清晰,减少重复代码,并提供更好的用户体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值