全局捕获异常类
spring 全局捕获异常类:
package com.xxx.emp.ControllerAdvice;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
@Component
public class ValidAdvice {
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public Map<String, Object> handleConstraintViolationException(ConstraintViolationException e){
Map<String, Object> map = new HashMap<>();
map.put("code",-444);
map.put("msg","参数验证不通过");
return map;
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public Map<String, Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
Map<String, Object> map = new HashMap<>();
map.put("code",-444);
map.put("msg","参数验证不通过");
return map;
}
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
public Map<String, Object> handleHttpMessageNotReadableException(HttpMessageNotReadableException e){
Map<String, Object> map = new HashMap<>();
map.put("code",-444);
map.put("msg","参数验证不通过");
return map;
}
}
@ControllerAdvice 与 @ExceptionHandler 注解
解释参考:https://www.jianshu.com/p/537509946453

浙公网安备 33010602011771号