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 File: GlobalControllerAdvice.java    From springdoc-openapi with 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 #2
Source File: BaseExceptionHandler.java    From charging_pile_cloud with 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 File: ExceptionAdvice.java    From MyCommunity with 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 #4
Source File: JeecgBootExceptionHandler.java    From teaching with 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 #5
Source File: ExceptionHandlerAdvice.java    From cloud-service with MIT License 5 votes vote down vote up
@ExceptionHandler({ IllegalArgumentException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, Object> badRequestException(IllegalArgumentException exception) {
	Map<String, Object> data = new HashMap<>();
	data.put("code", HttpStatus.BAD_REQUEST.value());
	data.put("message", exception.getMessage());

	return data;
}
 
Example #6
Source File: GlobleExceptionHandler.java    From zfile with MIT License 5 votes vote down vote up
/**
 * 初始化异常
 */
@ExceptionHandler({InitializeDriveException.class})
@ResponseBody
@ResponseStatus
public ResultBean initializeException(InitializeDriveException ex) {
    return ResultBean.error(ex.getMessage());
}
 
Example #7
Source File: ExceptionHandlerAdvice.java    From cloud-service with 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 #8
Source File: RestExceptionHandler.java    From plumemo with 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 #9
Source File: EndpointErrorHandler.java    From Mastering-Microservices-with-Java-Third-Edition with 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 #10
Source File: GlobalExceptionHand.java    From spring-boot-shiro with 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 #11
Source File: StackValidationExceptionHandler.java    From gaia with 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 #12
Source File: ExceptionHandlerAdvice.java    From open-capacity-platform with 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 #13
Source File: ComServExceptionHandler.java    From kardio with 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 #14
Source File: GlobalExceptionHandler.java    From mall with 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 #15
Source File: CommonExceptionHandler.java    From erp-framework with 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 #16
Source File: GlobalExceptionHand.java    From spring-boot-shiro with 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);
}
 
Example #17
Source File: GlobalExceptionHandler.java    From chronus with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param ex
 * @return
 * @throws Exception
 */
@ExceptionHandler(value = Exception.class)
public Response defaultErrorHandler(Exception ex) {
    log.error("", ex);
    Response response = new Response();
    response.setMsg(ex.getMessage());
    if (ex instanceof NoHandlerFoundException) {
        response.setCode("404");
    } else {
        response.setCode("500");
    }
    response.setFlag("F");
    return response;
}
 
Example #18
Source File: GlobalExceptionHandler.java    From springboot-link-admin with 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 #19
Source File: EndpointErrorHandler.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 5 votes vote down vote up
@ExceptionHandler(DuplicateBookingException.class)
public ResponseEntity<ErrorInfo> handleDuplicateRestaurantException(HttpServletRequest request,
    DuplicateBookingException 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 #20
Source File: TdsErrorHandling.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@ExceptionHandler(NcssException.class)
public ResponseEntity<String> handle(NcssException ex) {
  logger.warn("TDS Error", ex);

  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.setContentType(MediaType.TEXT_PLAIN);
  return new ResponseEntity<>("Invalid Request: " + htmlEscape(ex.getMessage()), responseHeaders,
      HttpStatus.BAD_REQUEST);
}
 
Example #21
Source File: GlobalDefaultExceptionHandler.java    From unified-dispose-springboot with Apache License 2.0 5 votes vote down vote up
/**
 * BindException 参数错误异常
 */
@ExceptionHandler(BindException.class)
public Result handleBindException(BindException e) throws Throwable {
    errorDispose(e);
    outPutError(BindException.class, CommonErrorCode.PARAM_ERROR, e);
    BindingResult bindingResult = e.getBindingResult();
    return getBindResultDTO(bindingResult);
}
 
Example #22
Source File: GlobalExceptionHandler.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
/**
 * 404 - Not Found
 */
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(NoHandlerFoundException.class)
public String noHandlerFoundException(NoHandlerFoundException e, Model model) {
    logger.error("Not Found", e);
    String message = "【页面不存在】" + e.getMessage();
    model.addAttribute("message", message);
    model.addAttribute("code", 404);
    System.out.println("404404错误");
    return viewName;
}
 
Example #23
Source File: BaseExceptionHandler.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(value = HttpMediaTypeNotSupportedException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public FebsResponse handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) {
    String message = "该方法不支持" + StringUtils.substringBetween(e.getMessage(), "'", "'") + "媒体类型";
    log.error(message);
    return new FebsResponse().message(message);
}
 
Example #24
Source File: EndpointErrorHandler.java    From Mastering-Microservices-with-Java-Third-Edition with MIT License 5 votes vote down vote up
@ExceptionHandler(BookingNotFoundException.class)
public ResponseEntity<ErrorInfo> handleRestaurantNotFoundException(HttpServletRequest request,
    BookingNotFoundException 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_FOUND);
}
 
Example #25
Source File: GlobalExceptionHandler.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(AuthServerException.class)
@ResponseBody
public CommonResponseDto handleAuthServerException(AuthServerException e) {
    String errMsg = String.format("Proccessing failed cause by %s:%s", e.getClass().getSimpleName(),
            e.getMessage() == null ? "" : e.getMessage());
    log.error(errMsg+"\n");
    return CommonResponseDto.error(e.getMessage() == null ? "Operation failed." : e.getMessage());
}
 
Example #26
Source File: ExceptionControllerAdvice.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
/**
 * 拦截参数异常
 *
 * @param e
 * @return
 */
@ResponseBody
@ExceptionHandler(value = IllegalArgumentException.class)
public MessageResult myErrorHandler(IllegalArgumentException e) {
    e.printStackTrace();
    log.info(">>>拦截参数异常>>",e);
    MessageResult result = MessageResult.error(e.getMessage());
    return result;
}
 
Example #27
Source File: GlobalExceptionHandler.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 处理所有运行时异常
 *
 * @param e
 * @return
 */
@ExceptionHandler(RuntimeException.class)
@ResponseBody
AjaxResult handleRuntimeException(RuntimeException e) {
    log.error("RuntimeException==>" + e.getMessage() + "\n" + e.getStackTrace());
    return AjaxResult.badRequest(e.getMessage());
}
 
Example #28
Source File: GlobalExceptionHandler.java    From supplierShop with MIT License 5 votes vote down vote up
/**
 * 系统异常
 */
@ExceptionHandler(Exception.class)
public AjaxResult handleException(Exception e)
{
    log.error(e.getMessage(), e);
    return AjaxResult.error("服务器错误,请联系管理员");
}
 
Example #29
Source File: ExceptionsHandler.java    From WeBASE-Transaction with Apache License 2.0 5 votes vote down vote up
/**
 * Exception Handler.
 * 
 * @param exc e
 * @return
 */
@ResponseBody
@ExceptionHandler(value = Exception.class)
public ResponseEntity exceptionHandler(Exception exc) {
    log.info("catch  exception", exc);
    RetCode retCode = ConstantCode.SYSTEM_ERROR;
    ResponseEntity rep = new ResponseEntity(retCode);
    try {
        log.warn("exceptionHandler system exception return:{}", mapper.writeValueAsString(rep));
    } catch (JsonProcessingException ex) {
        log.warn("exceptionHandler system exception");
    }
    return rep;
}
 
Example #30
Source File: GlobalExceptionHandler.java    From seata-samples with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler(DefaultException.class)
@ResponseBody
public ObjectResponse defaultException(DefaultException e){
    LOGGER.error("【系统抛出SinochemException异常】 —— 异常内容如下:{}" , e);
    ObjectResponse objectResponse = new ObjectResponse<>();
    objectResponse.setStatus(RspStatusEnum.FAIL.getCode());
    objectResponse.setMessage(RspStatusEnum.FAIL.getMessage());
    return objectResponse;
}