Java Code Examples for org.springframework.web.bind.annotation.ExceptionHandler

The following examples show how to use org.springframework.web.bind.annotation.ExceptionHandler. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: MyCommunity   Source File: ExceptionAdvice.java    License: Apache License 2.0 6 votes vote down vote up
@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");
    }
}
 
Example 2
Source Project: charging_pile_cloud   Source File: BaseExceptionHandler.java    License: MIT License 6 votes vote down vote up
@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();
}
 
Example 3
Source Project: teaching   Source File: JeecgBootExceptionHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @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());
}
 
Example 4
Source Project: springdoc-openapi   Source File: GlobalControllerAdvice.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 5
Source Project: ChengFeng1.5   Source File: ChengfengExceptionHandler.java    License: MIT License 5 votes vote down vote up
@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);
}
 
Example 6
@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);
}
 
Example 7
/**
 * 参数异常
 *
 * @param ex Exception
 */
@ExceptionHandler(ParamException.class)
@ResponseBody
public JsonData<Void> paramException(ParamException ex) {
    LogBack.error(ex.getMessage(), ex);
    return JsonData.failed(StatusEnum.PARAM_ILLEGAL);
}
 
Example 8
@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);
}
 
Example 9
Source Project: sk-admin   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 处理所有不可知的异常
 */
@ExceptionHandler(Throwable.class)
public ResponseEntity<ApiError> handleException(Throwable e) {
    // 打印堆栈信息
    log.error(ThrowableUtil.getStackTrace(e));
    return buildResponseEntity(ApiError.error(e.getMessage()));
}
 
Example 10
Source Project: sk-admin   Source File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example 11
@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);
}
 
Example 12
Source Project: cloud-service   Source File: ExceptionHandlerAdvice.java    License: MIT License 5 votes vote down vote up
/**
 * 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;
}
 
Example 13
Source Project: kvf-admin   Source File: ExceptHandler.java    License: MIT License 5 votes vote down vote up
@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());
}
 
Example 14
Source Project: springdoc-openapi   Source File: GlobalControllerAdvice.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 15
/**
    * 其他异常
    *
    * @param ex Exception
    */
   @ExceptionHandler(Exception.class)
   @ResponseBody
   public JsonData<Void> defaultException(Exception ex) {
       LogBack.error(ex.getMessage(), ex);
	return JsonData.failed(StatusEnum.SYSTEM_ERROR);
}
 
Example 16
@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;
}
 
Example 17
@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();
}
 
Example 18
Source Project: kylin-on-parquet-v2   Source File: BasicController.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 19
Source Project: mogu_blog_v2   Source File: RestExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 415错误
 *
 * @return
 */
@ExceptionHandler({HttpMediaTypeNotSupportedException.class})
@ResponseBody
public Result request415(HttpMediaTypeNotSupportedException ex) {
    log.error("异常类 HttpMediaTypeNotSupportedException {}", ex.getMessage());
    return Result.createWithErrorMessage("参数异常", ErrorConstants.PARAM_INCORRECT);
}
 
Example 20
Source Project: zfile   Source File: GlobleExceptionHandler.java    License: MIT License 5 votes vote down vote up
/**
 * 初始化异常
 */
@ExceptionHandler({InitializeDriveException.class})
@ResponseBody
@ResponseStatus
public ResultBean initializeException(InitializeDriveException ex) {
    return ResultBean.error(ex.getMessage());
}
 
Example 21
Source Project: plumemo   Source File: RestExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 400错误
 *
 * @param ex
 * @return
 */
@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseBody
public Result requestNotReadable(HttpMessageNotReadableException ex) {
    log.error("异常类 HttpMessageNotReadableException {},", ex.getMessage());
    return Result.createWithErrorMessage(ErrorEnum.PARAM_INCORRECT);
}
 
Example 22
@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);
}
 
Example 23
Source Project: spring-boot-shiro   Source File: GlobalExceptionHand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 24
@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);
}
 
Example 25
@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;
}
 
Example 26
@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;
}
 
Example 27
Source Project: kardio   Source File: ComServExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 28
Source Project: mall   Source File: GlobalExceptionHandler.java    License: MIT License 5 votes vote down vote up
@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();
}
 
Example 29
Source Project: erp-framework   Source File: CommonExceptionHandler.java    License: MIT License 5 votes vote down vote up
/**
 * 默认统一异常处理方法
 * @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;
}
 
Example 30
Source Project: spring-boot-shiro   Source File: GlobalExceptionHand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}