在spring 3.2中,新增了@ControllerAdvice 注解,可以用于定义@ExceptionHandler、@InitBinder、@ModelAttribute,并应用到所有@RequestMapping中。
GlobalExceptionHandler 异常处理类
import cc.ewell.dripping.product.vitalsigns.exception.BizException;
import cc.ewell.dripping.product.vitalsigns.exception.ErrorInfo;
import cc.ewell.dripping.product.vitalsigns.exception.ExceptionConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
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.bind.annotation.ResponseStatus;
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(value = BizException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorInfo jsonErrorHandler(BizException e) {
log.info("业务异常",e);
ErrorInfo r = new ErrorInfo();
r.setMessage(e.getMessage());
r.setCode(e.getCode());
return r;
}
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorInfo jsonErrorHandler(Exception e) {
log.error("系统异常",e);
ErrorInfo r = new ErrorInfo();
r.setMessage(e.getMessage());
r.setCode(“10000”);
return r;
}
}
ErrorInfo 类
public class ErrorInfo {
private String code;
private String message;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
BizException 类,spring 对于 RuntimeException 异常才会进行事务回滚。
public class BizException extends RuntimeException{
private String code;
private String message;
public BizException(String code, String message){
super(message);
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
测试类:
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("getAge")
public void getAge(@RequestParam("age") Integer age) {
if(age % 2 == 0){
throw new BizException("101","年龄为偶数");
}
}
}
访问:http://localhost:8080/user/getAge?age=20 页面会提示: