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;
/**
* @Author zengqifeng
* @CreateTime 2021/7/7 11:42
* @Description
*/
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Result exceptionHandler(Exception e) {
if (e instanceof ServiceException) {
ServiceException serviceException = (ServiceException) e;
return Result.error(serviceException.getCode(), serviceException.getMsg());
}else if(e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException me = (MethodArgumentNotValidException) e;
String defaultMessage = ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
return Result.error(1, defaultMessage);
}else {
return Result.error(1, e.getMessage());
}
}
}
springboot全局异常处理(参数校验)
最新推荐文章于 2024-02-04 09:45:23 发布