下面列出了怎么用org.springframework.web.bind.annotation.ExceptionHandler的API类实例代码及写法,或者点击链接到github查看源代码。
@ExceptionHandler({Exception.class})
public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.error("服务器发生异常: " + e.getMessage());
for (StackTraceElement element : e.getStackTrace()) {
logger.error(element.toString());
}
String xRequestedWith = request.getHeader("x-requested-with");
if ("XMLHttpRequest".equals(xRequestedWith)) {
response.setContentType("application/plain;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.write(JSONUtil.getJSONString(1, "服务器异常!"));
} else {
response.sendRedirect(request.getContextPath() + "/error");
}
}
@ExceptionHandler(value = Throwable.class)
@ResponseBody
public Map<String, Object> serverException(Throwable e) {
log.error("日志记录错误:\n{}", ExceptionUtils.getStackTrace(e));
if (e instanceof CommonException) {
return RequestException(e.getMessage());
}else if(e instanceof WxErrorException){
JSONObject jsonObject = JSONObject.parseObject(e.getMessage());
return RequestException(jsonObject.getString("errmsg"));
}else if(e instanceof WxPayException){
return RequestException(((WxPayException) e).getXmlString());
}else if(e instanceof HttpRequestMethodNotSupportedException){
return RequestException(e.getMessage());
}
return getExceptionMap();
}
/**
* @Author 政辉
* @param e
* @return
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result<?> HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
StringBuffer sb = new StringBuffer();
sb.append("不支持");
sb.append(e.getMethod());
sb.append("请求方法,");
sb.append("支持以下");
String [] methods = e.getSupportedMethods();
if(methods!=null){
for(String str:methods){
sb.append(str);
sb.append("、");
}
}
log.error(sb.toString(), e);
//return Result.error("没有权限,请联系管理员授权");
return Result.error(405,sb.toString());
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
public ResponseEntity<ErrorMessage> handleMethodArgumentNotValid(MethodArgumentNotValidException ex
) {
List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
List<String> errors = new ArrayList<>(fieldErrors.size() + globalErrors.size());
String error;
for (FieldError fieldError : fieldErrors) {
error = fieldError.getField() + ", " + fieldError.getDefaultMessage();
errors.add(error);
}
for (ObjectError objectError : globalErrors) {
error = objectError.getObjectName() + ", " + objectError.getDefaultMessage();
errors.add(error);
}
ErrorMessage errorMessage = new ErrorMessage(errors);
//Object result=ex.getBindingResult();//instead of above can allso pass the more detailed bindingResult
return new ResponseEntity(errorMessage, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(ParamException.class)
@ResponseBody
@ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseResult<Map<String,Object>> paramExceptionHandler(ParamException exception){
Map<String,Object> result= Maps.newHashMap();
result.put("error", exception.getMsg());
return ResponseResult.createByError(ResponseCode.ERROR.getCode()
,ResponseCode.ERROR.getDesc(),result);
}
@ExceptionHandler
public ResponseEntity<Problem> handleNoSuchElementException(NoSuchElementException ex, NativeWebRequest request) {
Problem problem = Problem.builder()
.withStatus(Status.NOT_FOUND)
.with(MESSAGE_KEY, ErrorConstants.ENTITY_NOT_FOUND_TYPE)
.build();
return create(ex, problem, request);
}
/**
* 参数异常
*
* @param ex Exception
*/
@ExceptionHandler(ParamException.class)
@ResponseBody
public JsonData<Void> paramException(ParamException ex) {
LogBack.error(ex.getMessage(), ex);
return JsonData.failed(StatusEnum.PARAM_ILLEGAL);
}
@ExceptionHandler(DuplicateException.class)
public ResponseEntity<ErrorInfo> handleDuplicateRestaurantException(HttpServletRequest request,
DuplicateException ex, Locale locale) {
ErrorInfo response = new ErrorInfo();
response.setUrl(request.getRequestURL().toString());
response.setMessage(messageSource.getMessage(ex.getMessage(), ex.getArgs(), locale));
return new ResponseEntity<>(response, HttpStatus.IM_USED);
}
/**
* 处理所有不可知的异常
*/
@ExceptionHandler(Throwable.class)
public ResponseEntity<ApiError> handleException(Throwable e) {
// 打印堆栈信息
log.error(ThrowableUtil.getStackTrace(e));
return buildResponseEntity(ApiError.error(e.getMessage()));
}
/**
* BadCredentialsException
*/
@ExceptionHandler(BadCredentialsException.class)
public ResponseEntity<ApiError> badCredentialsException(BadCredentialsException e) {
// 打印堆栈信息
String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage();
log.error(message);
return buildResponseEntity(ApiError.error(message));
}
@ExceptionHandler(InvalidBookingException.class)
public ResponseEntity<ErrorInfo> handleInvalidRestaurantException(HttpServletRequest request,
InvalidBookingException ex, Locale locale) {
ErrorInfo response = new ErrorInfo();
response.setUrl(request.getRequestURL().toString());
response.setMessage(messageSource.getMessage(ex.getMessage(), ex.getArgs(), locale));
return new ResponseEntity<>(response, HttpStatus.NOT_ACCEPTABLE);
}
/**
* feignClient调用异常,将服务的异常和http状态码解析
*
* @param exception
* @param response
* @return
*/
@ExceptionHandler({ FeignException.class })
public Map<String, Object> feignException(FeignException exception, HttpServletResponse response) {
int httpStatus = exception.status();
if (httpStatus >= 500) {
log.error("feignClient调用异常", exception);
}
Map<String, Object> data = new HashMap<>();
String msg = exception.getMessage();
if (!StringUtils.isEmpty(msg)) {
int index = msg.indexOf("\n");
if (index > 0) {
String string = msg.substring(index);
if (!StringUtils.isEmpty(string)) {
JSONObject json = JSONObject.parseObject(string.trim());
data.putAll(json.getInnerMap());
}
}
}
if (data.isEmpty()) {
data.put("message", msg);
}
data.put("code", httpStatus + "");
response.setStatus(httpStatus);
return data;
}
@ExceptionHandler(KvfException.class)
public R handleKvfException(KvfException e) {
LOGGER.error("kvf-admin error:", e);
if (e.getErrorCode() == null) {
return R.fail(e.getMsg());
}
return R.fail(e.getErrorCode(), e.getMsg());
}
@ExceptionHandler(Throwable.class)
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<Problem> problem(final Throwable e) {
String message = e.getMessage();
//might actually prefer to use a geeric mesasge
message = "Problem occured";
UUID uuid = UUID.randomUUID();
String logRef = uuid.toString();
logger.error("logRef=" + logRef, message, e);
return new ResponseEntity<Problem>(new Problem(logRef, message), HttpStatus.INTERNAL_SERVER_ERROR);
}
/**
* 其他异常
*
* @param ex Exception
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public JsonData<Void> defaultException(Exception ex) {
LogBack.error(ex.getMessage(), ex);
return JsonData.failed(StatusEnum.SYSTEM_ERROR);
}
@ExceptionHandler(Exception.class)
public ModelAndView handleException
(HttpServletRequest request, Exception ex){
ModelAndView mv = new ModelAndView();
mv.addObject("exception", ex.getLocalizedMessage());
mv.addObject("url", request.getRequestURL());
mv.setViewName("error");
return mv;
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
public void processMethod(Exception e, HttpServletRequest request,
HttpServletResponse response) throws IOException {
LOGGER.error("abnormal server:{}", e.getLocalizedMessage());
response.setCharacterEncoding(ConstantsUnicode.UTF8);
response.setContentType("application/json; charset=utf-8");
APIResponseDTO apiResponseDTO = new APIResponseDTO();
apiResponseDTO.setResponse(APIResponseStatus.INTERNAL_SERVER_ERROR);
ObjectMapper mapper = new ObjectMapper();
String responseJson = mapper.writeValueAsString(apiResponseDTO);
response.getWriter().printf(responseJson);
response.flushBuffer();
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
@ResponseBody
ErrorResponse handleError(HttpServletRequest req, Exception ex) {
logger.error("", ex);
return new ErrorResponse(req.getRequestURL().toString(), ex);
}
/**
* 415错误
*
* @return
*/
@ExceptionHandler({HttpMediaTypeNotSupportedException.class})
@ResponseBody
public Result request415(HttpMediaTypeNotSupportedException ex) {
log.error("异常类 HttpMediaTypeNotSupportedException {}", ex.getMessage());
return Result.createWithErrorMessage("参数异常", ErrorConstants.PARAM_INCORRECT);
}
/**
* 初始化异常
*/
@ExceptionHandler({InitializeDriveException.class})
@ResponseBody
@ResponseStatus
public ResultBean initializeException(InitializeDriveException ex) {
return ResultBean.error(ex.getMessage());
}
/**
* 400错误
*
* @param ex
* @return
*/
@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseBody
public Result requestNotReadable(HttpMessageNotReadableException ex) {
log.error("异常类 HttpMessageNotReadableException {},", ex.getMessage());
return Result.createWithErrorMessage(ErrorEnum.PARAM_INCORRECT);
}
@ExceptionHandler(DuplicateRestaurantException.class)
public ResponseEntity<ErrorInfo> handleDuplicateRestaurantException(HttpServletRequest request,
DuplicateRestaurantException ex, Locale locale) {
ErrorInfo response = new ErrorInfo();
response.setUrl(request.getRequestURL().toString());
response.setMessage(messageSource.getMessage(ex.getMessage(), ex.getArgs(), locale));
return new ResponseEntity<>(response, HttpStatus.IM_USED);
}
/**
* 401 - Unauthorized
*/
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(LoginException.class)
public Response handleLoginException(LoginException e) {
String msg = e.getMessage();
log.error("登录异常:", e);
return new Response().failure(msg);
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public Map<String, String> handleValidationExceptions(MethodArgumentNotValidException ex) {
var message = ex.getBindingResult().getAllErrors().stream()
.map(this::getMessage)
.collect(Collectors.joining("\n"));
return Map.of("message", message);
}
@ExceptionHandler({ StatusRuntimeException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, Object> badRequestException(StatusRuntimeException exception) {
Map<String, Object> data = new HashMap<>();
data.put("resp_code", HttpStatus.INTERNAL_SERVER_ERROR.value());
data.put("resp_msg", exception.getMessage());
return data;
}
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResponseResult jsonErrorHandler(HttpServletRequest req, Exception e)
throws Exception {
ResponseResult r = new ResponseResult();
r.setCode(AppContext.CODE_50000);
r.setMsg("系统异常");
return r;
}
@ExceptionHandler(Throwable.class)
ResponseEntity<Object> handleControllerException(HttpServletRequest req, Throwable ex) {
log.error("Got Exception", ex);
GDMResponse errorResponse = new GDMResponse(ex);
PrometheusMetricService.setRequestStatus(req, "unknown-error");
return new ResponseEntity<Object>(errorResponse, HttpStatus.OK);
}
@ExceptionHandler(ValidationException.class)
@ResponseBody
public Object badArgumentHandler(ValidationException e) {
e.printStackTrace();
if (e instanceof ConstraintViolationException) {
ConstraintViolationException exs = (ConstraintViolationException) e;
Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
for (ConstraintViolation<?> item : violations) {
String message = ((PathImpl) item.getPropertyPath()).getLeafNode().getName() + item.getMessage();
return ResponseUtil.fail(402, message);
}
}
return ResponseUtil.badArgumentValue();
}
/**
* 默认统一异常处理方法
* @param e 默认Exception异常对象
* @return
*/
@ExceptionHandler
public ResultBean<String> runtimeExceptionHandler(Exception e) {
logger.error("运行时异常:【{}】", e.getMessage(),e);
ResultBean<String> result= new ResultBean<>();
result.setCode(ExceptionEnum.SERVER_ERROR.getCode());
result.setMsg(e.getMessage()+"-- traceid:"+ MDC.get("traceId"));
return result;
}
/**
* 422 - UNPROCESSABLE_ENTITY
*/
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(MaxUploadSizeExceededException.class)
public Response handleMaxUploadSizeExceededException(Exception e) {
String msg = "所上传文件大小超过最大限制,上传失败!";
log.error(msg, e);
return new Response().failure(msg);
}