spring 统一异常拦截 ,定制自己的返回code以及返回的message

新建如下JAVA文件即可



@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

private String profile;

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseObj bindException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();

StringBuffer errorMesssage = new StringBuffer();

for (FieldError fieldError : bindingResult.getFieldErrors()) {
errorMesssage .append(fieldError.getDefaultMessage() + ", ");
}
// 此处代码为项目内统一返回java类 这里不做该类展示
ResponseObj response = ResponseObj.setResultCode(ResultCode.FAIL_ILLEGAL_ARGUMENT);
response.getStatus().setMessage(errorMesssage.toString());

return response;
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseObj exception(Exception ex) {
log.error("", ex);
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
ResponseObj response =ResponseObj.setResultCode(ResultCode.FAIL_UNKNOWN,stringWriter.toString());
return response;
}

}

转载于:https://www.cnblogs.com/xiaohan666/p/9805608.html

你可能感兴趣的:(spring 统一异常拦截 ,定制自己的返回code以及返回的message)