可以通过@ControllerAdvice注解来进行统一异常处理。
一、自定义异常时返回的json格式:
package com.example.controller;
public class MyErrorBody {
private int status;
private String message;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public MyErrorBody(int status, String message) {
this.status = status;
this.message = message;
}
}
二、定义包含@ControllerAdvice的统一异常处理类:
package com.example.controller;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
//@ControllerAdvice(basePackageClasses = FirstController.class)
@ControllerAdvice(basePackages = {"com.example"})
public class MyControllerAdvice extends ResponseEntityExceptionHandler {
@ResponseBody
@ExceptionHandler(ArithmeticException.class)
public ResponseEntity<?> handleControllerException(HttpServletRequest request,
Throwable ex) {
HttpStatus status = getStatus(request);
return new ResponseEntity<>(new MyErrorBody(status.value(), ex.getMessage()),
status);
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer code = (Integer)
request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if(code==null){
return HttpStatus.INTERNAL_SERVER_ERROR;
}
HttpStatus status = HttpStatus.resolve(code);
return (status != null) ? status : HttpStatus.INTERNAL_SERVER_ERROR;
}
}
其中@ControllerAdvice注解的basePackages是个字符串数组,可以指定要进行统一处理的包名;也可以通过basePackageClasses来直接指定要进行统一处理的类,这个属性同样是字符串数组。
handleControllerException方法上的@ExceptionHandler注解中可以指定要处理的异常类型
三、定义controller,包含抛出异常的接口
package com.example.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedList;
import java.util.List;
@RestController
public class FirstController {
@GetMapping("/getInfo")
public String getInfo(){
int t=1/0;
return "info";
}
}
四、postman调用,从结果可以看到返回了自定义的json格式