SpringBoot 自定义异常处理

自定义异常处理可以帮助我们更好地管理应用程序中的异常,并返回统一的错误响应。

1. 自定义异常类

定义自己的异常类,继承自 RuntimeException 或其他异常类。

public class MyException extends RuntimeException {
    
    
    private String msg;
    public MyException(String msg) {
    
    
        super(msg);
        this.msg = msg;
    }

    public String getMsg() {
    
    
        return msg;
    }

    public void setMsg(String msg) {
    
    
        this.msg = msg;
    }
}

2. 使用 @ControllerAdvice 和 @ExceptionHandler

@ControllerAdvice 是一个全局的异常处理类,它可以处理整个应用程序中抛出的异常。@ExceptionHandler 用于指定处理特定异常的方法。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class MyExceptionHandler {
    
    

    @ExceptionHandler(MyException.class)
    public ResponseEntity<String> MyExceptionHandle(Exception e){
    
    
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> exceptionHandle(Exception e){
    
    
        e.printStackTrace();
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
    }

}

3. 创建控制器类,在 Controller 中抛出异常

import com.qvtu.web.exception.MyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/dish")
public class DishController {
    
    
    @RequestMapping("/del/{i}")
    public ResponseEntity<String> delDish(@PathVariable String i) {
    
    
        Integer id=Integer.valueOf(i);
        if (id<0){
    
    
            throw  new MyException("参数错误!");
        }
        return new ResponseEntity<>("del success", HttpStatus.OK);
    }
}

4. 运行测试

启动程序,在浏览器中访问http://localhost:8080/dish/del/1
在这里插入图片描述
在浏览器中访问http://localhost:8080/dish/del/-1
在这里插入图片描述
在浏览器中访问http://localhost:8080/dish/del/a
在这里插入图片描述