1.定义全局算术异常处理器,返回格式为:{"msg":"算术异常","code":-1} * 2.定义全局空指针异常处理器,返回格式为:{"msg":"空指针异常","code":-2}
时间: 2024-11-22 22:29:07 浏览: 4
springboot定义统一返回格式及全局异常处理
在Spring MVC中,你可以通过创建一个带有`@ControllerAdvice`注解的类,并在里面定义两个`@ExceptionHandler`方法来实现全局异常处理器。这里是一个例子:
```java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ArithmeticException.class)
public ResponseEntity<ErrorResponse> handleArithmeticException(ArithmeticException e) {
ErrorResponse response = new ErrorResponse();
response.setMsg("算术异常");
response.setCode(-1);
return ResponseEntity.badRequest().body(response);
}
@ExceptionHandler(NullPointerException.class)
public ResponseEntity<ErrorResponse> handleNullPointerException(NullPointerException e) {
ErrorResponse response = new ErrorResponse();
response.setMsg("空指针异常");
response.setCode(-2);
return ResponseEntity.serverError().body(response);
}
private static class ErrorResponse {
private String msg;
private int code;
// getters and setters...
}
阅读全文