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

The following examples show how to use org.springframework.web.bind.annotation.ExceptionHandler. 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   Author: UHungLin   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   Author: konglingyinxia   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   Author: open-scratch   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   Author: springdoc   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   Author: fuyunwang   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
Source Project: java-microservices-examples   Author: oktadeveloper   File: ExceptionTranslator.java    License: Apache License 2.0 5 votes vote down vote up
@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
Source Project: codeway_service   Author: GuoGuang   File: SystemExceptionHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 参数异常
 *
 * @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
Source Project: Mastering-Microservices-with-Java-Third-Edition   Author: PacktPublishing   File: EndpointErrorHandler.java    License: MIT License 5 votes vote down vote up
@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   Author: DengSinkiang   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   Author: DengSinkiang   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
Source Project: Mastering-Microservices-with-Java-Third-Edition   Author: PacktPublishing   File: EndpointErrorHandler.java    License: MIT License 5 votes vote down vote up
@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   Author: allenyiwen   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   Author: kalvinGit   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   Author: springdoc   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
Source Project: codeway_service   Author: GuoGuang   File: SystemExceptionHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
    * 其他异常
    *
    * @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
Source Project: pcf-crash-course-with-spring-boot   Author: in28minutes   File: ErrorController.java    License: MIT License 5 votes vote down vote up
@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
Source Project: singleton   Author: vmware   File: TranslationSyncServerController.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@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   Author: Kyligence   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   Author: moxi624   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   Author: zhaojun1998   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   Author: byteblogs168   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
Source Project: Mastering-Microservices-with-Java-Third-Edition   Author: PacktPublishing   File: EndpointErrorHandler.java    License: MIT License 5 votes vote down vote up
@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   Author: MRLEILOVE   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
Source Project: gaia   Author: gaia-app   File: StackValidationExceptionHandler.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@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
Source Project: open-capacity-platform   Author: open-capacity-platform   File: ExceptionHandlerAdvice.java    License: Apache License 2.0 5 votes vote down vote up
@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
Source Project: springboot-link-admin   Author: 252956   File: GlobalExceptionHandler.java    License: Apache License 2.0 5 votes vote down vote up
@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   Author: tmobile   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   Author: bigspiders   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   Author: chyanwu   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   Author: MRLEILOVE   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);
}