SpringBoot全局异常与数据校验
1.全局异常控制类加入拦截
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 全局验证异常类
*
*
* @param request
* @param exception
* @return
*/
//添加全局异常处理流程,根据需要设置需要处理的异常
@ExceptionHandler(value = BindException.class)
@ResponseBody
public Object validatorServiceExceptionHandler(HttpServletRequest request, BindException exception)throws Exception{
//字段验证
// ResponseMessage responseMessage = new ResponseMessage();
// //获取校验错误信息
// if (bindingResult.hasErrors()) {
// // 校验失败,获取校验错误信息
// List<FieldError> errors = bindingResult.getFieldErrors();
// StringBuilder sb = new StringBuilder();
// for (FieldError error : errors) {
// sb.append(error.getDefaultMessage()).append(";");
// }
// responseMessage.setMsg(sb.toString());
// responseMessage.setCode(UserCenterStatusCode.VERIFY_ERROR.getCode());//验证失败
// return responseMessage;
// }
//按需重新封装需要返回的错误信息
List<ResponseMessage> paramValidationResults = new ArrayList<>();
//解析原错误信息,封装后返回,此处返回非法的字段名称,错误信息
for (FieldError error : exception.getBindingResult().getFieldErrors()) {
ResponseMessage validationResult = new ResponseMessage();
// validationResult.setMessage(error.getDefaultMessage());
// validationResult.setParam(error.getField());
validationResult.setMsg(error.getDefaultMessage());
validationResult.setCode(UserCenterStatusCode.VERIFY_ERROR.getCode());//验证失败
paramValidationResults.add(validationResult);
return validationResult;
}
return null;
}
@ExceptionHandler(ProductServiceException.class)
@ResponseBody
public ErrorMessage<String> productServiceExceptionHandler(HttpServletRequest request, ProductServiceException exception) throws Exception {
return handleErrorInfo(request, exception.getMessage(), exception);
}
@ExceptionHandler(OrderSerivceException.class)
@ResponseBody
public ErrorMessage<String> orderSerivceExceptionHandler(HttpServletRequest request, OrderSerivceException exception) throws Exception {
return handleErrorInfo(request, exception.getMessage(), exception);
}
@ExceptionHandler(MessageServiceException.class)
@ResponseBody
public ErrorMessage<String> messageServiceExceptionHandler(HttpServletRequest request, MessageServiceException exception) throws Exception {
return handleErrorInfo(request, exception.getMessage(), exception);
}
@ExceptionHandler(MemberServiceException.class)
@ResponseBody
public ErrorMessage<String> memberServiceExceptionHandler(HttpServletRequest request, MemberServiceException exception) throws Exception {
return handleErrorInfo(request, exception.getMessage(), exception);
}
@ExceptionHandler(ManageServiceException.class)
@ResponseBody
public ErrorMessage<String> manageServiceExceptionHandler(HttpServletRequest request, ManageServiceException exception) throws Exception {
return handleErrorInfo(request, exception.getMessage(), exception);
}
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public ErrorMessage<String> noHandlerFoundHandler(HttpServletRequest request, Exception exception) throws Exception {
ErrorMessage<String> errorMessage = new ErrorMessage<>();
errorMessage.setMessage(HttpStatus.NOT_FOUND.name());
errorMessage.setCode(HttpStatus.NOT_FOUND.value());
errorMessage.setData(exception.getMessage());
errorMessage.setUrl(request.getRequestURL().toString());
return errorMessage;
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorMessage<String> exceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
return handleErrorInfo(request, exception.toString(), exception);
}
@ExceptionHandler(IOException.class)
@ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
@ResponseBody
public ErrorMessage<String> ioEexceptionHandler(HttpServletRequest request, Exception exception) throws Exception {
if (StringUtils.containsIgnoreCase(ExceptionUtils.getRootCauseMessage(exception), "Broken pipe")){
return null;
} else {
return handleErrorInfo(request, exception.toString(), exception);
}
}
private ErrorMessage<String> handleErrorInfo(HttpServletRequest request, String message, Exception exception) {
ErrorMessage<String> errorMessage = new ErrorMessage<>();
errorMessage.setMessage(message);
errorMessage.setCode(ErrorMessage.ERROR);
errorMessage.setData(getStackMsg(exception));
errorMessage.setUrl(request.getRequestURL().toString());
return errorMessage;
}
private static String getStackMsg(Exception e) {
StringBuffer sb = new StringBuffer();
StackTraceElement[] stackArray = e.getStackTrace();
for (int i = 0; i < stackArray.length; i++) {
StackTraceElement element = stackArray[i];
sb.append(element.toString() + "\n");
}
return sb.toString();
}
private static String getStackMsg(Throwable e) {
StringBuffer sb = new StringBuffer();
StackTraceElement[] stackArray = e.getStackTrace();
for (int i = 0; i < stackArray.length; i++) {
StackTraceElement element = stackArray[i];
sb.append(element.toString() + "\n");
}
return sb.toString();
}
2.重要注解说明:
(1)这里@ControllerAdvice注解标注,@ControllerAdvice是@Controller的增强版,一般与@ExceptionHandler搭配使用。
如果标注@Controller,异常处理只会在当前controller类中的方法起作用,但是使用@ControllerAdvice,则全局有效。
(2)@ExceptionHandler注解里面填写想要捕获的异常类class对象
3.编写实体 ,并对属性进行注解控制
4.测试controller【主要是添加@Validated注解】
/**
* 完善个人用户信息(即修改个人用户信息)
*
*
* @param ciipPersonalUserVO 个人用户信息[所有信息]
* @return
*/
@ApiOperation(value="完善个人用户信息", notes = "")
@PostMapping(value = CIIPCommonConstant.ApiAuth.AUTHC + "/perfectCiipPersonalUserInfo")
public ResponseMessage perfectCiipPersonalUserInfo(@Validated CiipPersonalUserVO ciipPersonalUserVO)throws Exception{
return ciipPersonalUserService.perfectCiipPersonalUserInfo(ciipPersonalUserVO);
}
5.postMan验证结果