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

The following are top voted examples for showing how to use org.springframework.web.bind.annotation.ExceptionHandler. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: xm-commons   File: ExceptionTranslator.java   Source Code and License 8 votes vote down vote up
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorVM> processException(Exception ex) {
    log.error("An unexpected error occurred: {}", ex.getMessage(), ex);
    BodyBuilder builder;
    ErrorVM errorVM;
    ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class);
    if (responseStatus != null) {
        builder = ResponseEntity.status(responseStatus.value());
        errorVM = new ErrorVM(ERROR_PREFIX + responseStatus.value().value(),
                              translate(ERROR_PREFIX + responseStatus.value().value()));
    } else {
        builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR,
                              translate(ErrorConstants.ERR_INTERNAL_SERVER_ERROR));
    }
    return builder.body(errorVM);
}
 
Example 2
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 8 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!   ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append(" root cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 3
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 7 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!  ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append("\n\nroot cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 4
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 6 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!   ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append(" root cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 5
Project: meparty   File: ValidationErrorHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Rest handler for validation errors.
 * @param ex handled exception
 * @return rest result
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<?> processHandler(MethodArgumentNotValidException ex) {

  BindingResult bindingResult = ex.getBindingResult();
  List<FieldError> fieldErrors = bindingResult.getFieldErrors();
  List<FieldErrorDto> fieldErrorDtos = fieldErrors.stream()
      .map(FieldErrorDto::new)
      .collect(Collectors.toList());

  ValidationResultDto validationResultDto = new ValidationResultDto();
  validationResultDto.setFieldErrors(fieldErrorDtos);

  LOGGER.error("VALIDATION ERROR: " + ex.getMessage());

  return ResponseEntity.badRequest().body(validationResultDto);
}
 
Example 6
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 6 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!  ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    sb.append(", root cause: ").append((throwable != null && throwable.getCause() != null ? throwable.getCause() : "Unknown cause"));
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 7
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 6 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!  ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append("\n\nroot cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 8
Project: open-kilda   File: TopologyExceptionHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Handles MessageException exception.
 *
 * @param exception the MessageException instance
 * @param request   the WebRequest caused exception
 * @return the ResponseEntity object instance
 */
@ExceptionHandler(MessageException.class)
protected ResponseEntity<Object> handleMessageException(MessageException exception, WebRequest request) {
    HttpStatus status;

    switch (exception.getErrorType()) {
        case NOT_FOUND:
            status = HttpStatus.NOT_FOUND;
            break;
        case DATA_INVALID:
        case PARAMETERS_INVALID:
            status = HttpStatus.BAD_REQUEST;
            break;
        case ALREADY_EXISTS:
            status = HttpStatus.CONFLICT;
            break;
        case AUTH_FAILED:
            status = HttpStatus.UNAUTHORIZED;
            break;
        case OPERATION_TIMED_OUT:
        case INTERNAL_ERROR:
        default:
            status = HttpStatus.INTERNAL_SERVER_ERROR;
            break;
    }

    MessageError error = new MessageError(request.getHeader(CORRELATION_ID), exception.getTimestamp(),
            status.value(), status.getReasonPhrase(),
            exception.getMessage(), exception.getClass().getSimpleName());
    return super.handleExceptionInternal(exception, error, new HttpHeaders(), status, request);
}
 
Example 9
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 6 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!   ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append(" root cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 10
Project: sentry   File: ExceptionTranslator.java   Source Code and License 6 votes vote down vote up
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorVM> processRuntimeException(Exception ex) {
    log.debug("Processing runtime exception", ex);
    BodyBuilder builder;
    ErrorVM errorVM;
    ResponseStatus responseStatus = AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class);
    if (responseStatus != null) {
        builder = ResponseEntity.status(responseStatus.value());
        errorVM = new ErrorVM("error." + responseStatus.value().value(), responseStatus.reason());
    } else {
        builder = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR);
        errorVM = new ErrorVM(ErrorConstants.ERR_INTERNAL_SERVER_ERROR, "Internal server error");
    }
    return builder.body(errorVM);
}
 
Example 11
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 6 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!  ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append("\n\nroot cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 12
Project: cas-5.1.0   File: AbstractManagementController.java   Source Code and License 6 votes vote down vote up
/**
 * Resolve exception.
 *
 * @param request the request
 * @param response the response
 * @param ex the exception
 * @return the model and view
 * @throws IOException the iO exception
 */
@ExceptionHandler
public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response,
                                     final Exception ex) throws IOException {
    LOGGER.error(ex.getMessage(), ex);
    final String contentType = request.getHeader(AJAX_REQUEST_HEADER_NAME);
    if (contentType != null && contentType.equals(AJAX_REQUEST_HEADER_VALUE)) {
        LOGGER.debug("Handling exception [{}] for ajax request indicated by header [{}]",
                ex.getClass().getName(), AJAX_REQUEST_HEADER_NAME);
        JsonUtils.renderException(ex, response);
        return null;
    }
    LOGGER.trace("Unable to resolve exception [{}] for request. AJAX request header [{}] not found.",
            ex.getClass().getName(), AJAX_REQUEST_HEADER_NAME);
    final ModelAndView mv = new ModelAndView("error");
    mv.addObject(ex);
    return mv;
}
 
Example 13
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 6 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!   ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append(" root cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 14
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 6 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!  ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append("\n\nroot cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 15
Project: siga   File: GlobalExceptionHandler.java   Source Code and License 6 votes vote down vote up
@ExceptionHandler(value = Exception.class)
public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
	
	logger.error("[URL] : {}", req.getRequestURL(), e);
	
	// If the exception is annotated with @ResponseStatus rethrow it and let
	// the framework handle it - like the OrderNotFoundException example
	// at the start of this post.
	// AnnotationUtils is a Spring Framework utility class.
	if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
		throw e;

	// Otherwise setup and send the user to a default error-view.
	ModelAndView mav = new ModelAndView();
	mav.addObject("exception", e);
	mav.addObject("url", req.getRequestURL());
	mav.setViewName(DEFAULT_ERROR_VIEW);
	return mav;
}
 
Example 16
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 6 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ModelAndView exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    StringBuffer sb = new StringBuffer();
    sb.append("Exception during execution of Spring Security application!   ");

    sb.append((throwable != null && throwable.getMessage() != null ? throwable.getMessage() : "Unknown error"));

    if (throwable != null && throwable.getCause() != null) {
        sb.append(" root cause: ").append(throwable.getCause());
    }
    model.addAttribute("error", sb.toString());

    ModelAndView mav = new ModelAndView();
    mav.addObject("error", sb.toString());
    mav.setViewName("error");

    return mav;
}
 
Example 17
Project: metamodel-membrane   File: RestErrorHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Method binding issues (raised by Spring framework) - mapped to BAD_REQUEST.
 * 
 * @param ex
 * @return
 */
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public RestErrorResponse processValidationError(MethodArgumentNotValidException ex) {
    final BindingResult result = ex.getBindingResult();

    final Map<String, Object> globalErrorsMap = new LinkedHashMap<>();
    final List<ObjectError> globalErrors = result.getGlobalErrors();
    for (ObjectError objectError : globalErrors) {
        globalErrorsMap.put(objectError.getObjectName(), objectError.getDefaultMessage());
    }

    final List<FieldError> fieldErrors = result.getFieldErrors();
    final Map<String, Object> fieldErrorsMap = new LinkedHashMap<>();
    for (FieldError fieldError : fieldErrors) {
        fieldErrorsMap.put(fieldError.getObjectName() + '.' + fieldError.getField(),
                fieldError.getDefaultMessage());
    }

    final Map<String, Object> additionalDetails = new LinkedHashMap<>();
    if (!globalErrorsMap.isEmpty()) {
        additionalDetails.put("global-errors", globalErrorsMap);
    }
    if (!fieldErrorsMap.isEmpty()) {
        additionalDetails.put("field-errors", fieldErrorsMap);
    }
    final RestErrorResponse errorResponse =
            new RestErrorResponse(HttpStatus.BAD_REQUEST.value(), "Failed to validate request");
    if (!additionalDetails.isEmpty()) {
        errorResponse.setAdditionalDetails(additionalDetails);
    }
    return errorResponse;
}
 
Example 18
Project: spring-cloud-skipper   File: ReleaseController.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(PackageDeleteException.class)
public ResponseEntity<Map<String, String>> handlePackageDeleteException(PackageDeleteException error) {
	// TODO investigate why SkipperErrorAttributes is not being invoked.
	Map<String, String> map = new HashMap<>();
	map.put("exception", error.getClass().getName());
	map.put("message", error.getMessage());
	return new ResponseEntity<Map<String, String>>(map, HttpStatus.CONFLICT);
}
 
Example 19
Project: metamodel-membrane   File: RestErrorHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Catch-all exception handler method - mapped to INTERNAL_SERVER_ERROR.
 * 
 * @param ex
 * @return
 */
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public RestErrorResponse processAnyException(HttpServletRequest req, Exception ex) {
    logger.error("{} {} - Unexpected error!", req.getMethod(), req.getRequestURI(), ex);
    final Map<String, Object> additionalDetails = new HashMap<>();
    additionalDetails.put("exception_type", ex.getClass().getName());
    return new RestErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage(), additionalDetails);
}
 
Example 20
Project: playground-scenario-generator   File: RestResponseEntityExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<ErrorResponse> exceptionHandler(HttpServletRequest request, Exception e) {
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR.value())
            .contentType(MediaType.APPLICATION_JSON)
            .body(new ErrorResponse(e.getMessage()));
}
 
Example 21
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    String errorMessage = (throwable != null ? throwable.getMessage() : "Unknown error");
    model.addAttribute("error", errorMessage);
    return "error";
}
 
Example 22
Project: xxproject   File: CustomRestExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler({ ConstraintViolationException.class })
public ResponseEntity<Object> handleConstraintViolation(final ConstraintViolationException ex, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final List<String> errors = new ArrayList<String>();
    for (final ConstraintViolation<?> violation : ex.getConstraintViolations()) {
        errors.add(violation.getRootBeanClass().getName() + " " + violation.getPropertyPath() + ": " + violation.getMessage());
    }

    final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), errors);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example 23
Project: metamodel-membrane   File: RestErrorHandler.java   Source Code and License 5 votes vote down vote up
/**
 * Query parsing exception - mapped to BAD_REQUEST.
 * 
 * @param ex
 * @return
 */
@ExceptionHandler(QueryParserException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public RestErrorResponse processQueryParsingError(QueryParserException ex) {
    return new RestErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
}
 
Example 24
Project: counter-cloud   File: CounterApiControllerAdvice.java   Source Code and License 5 votes vote down vote up
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Throwable.class)
public String unknownException(Throwable exception) {
    log(exception);

    return messageSourceAccessor.getMessage("error.unknown", new Object[]{exception.getMessage()});
}
 
Example 25
Project: sweiproject-tg2b-1   File: ExceptionController.java   Source Code and License 5 votes vote down vote up
/**
 * Dealing a thrown exception {@link Exception}.
 *
 * @param exception thrown {@link Exception}.
 * @param request   from the client.
 * @return a new response entity.
 */
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleInternal(Exception exception, WebRequest request) {
    logger.error("500 Status Code", exception);
    final GenericResponse bodyOfResponse = new GenericResponse(message.getMessage("message.internalServerError",
            null, request.getLocale()), "InternalServerError");
    return new ResponseEntity<>(bodyOfResponse, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
}
 
Example 26
Project: nixmash-blog   File: GlobalController.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(ContactNotFoundException.class)
public ModelAndView handleContactNotFoundException() {
    logger.debug("In ContactNotFound Exception Handler");

    ModelAndView mav = new ModelAndView();
    mav.addObject(ERROR_PAGE_TITLE_ATTRIBUTE, "Contact Missing in Action!");
    mav.addObject(ERROR_PAGE_MESSAGE_ATTRIBUTE, "We'll find the rascal, don't you worry");
    mav.setViewName(ERROR_CUSTOM_VIEW);
    return mav;
}
 
Example 27
Project: PowerApi   File: UnauthorizedExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler({UnknownSessionException.class})
public ModelAndView processUnknownSessionException(NativeWebRequest request, MissingServletRequestParameterException e) {
    ModelAndView mv = new ModelAndView();
    mv.addObject("exception", e.getMessage());
    mv.setViewName("/signin");
    return mv;
}
 
Example 28
Project: logistimo-web-service   File: ErrorHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler({ForbiddenAccessException.class})
protected ResponseEntity<Object> handleForbiddenAccessException(ForbiddenAccessException e,
                                                                WebRequest request) {
  logWarning(request, e);
  String message = e.getMessage();
  if (StringUtils.isBlank(message)) {
    message = ExceptionUtils.constructMessage("G003",
        getLocale(), null);
  }
  ErrorResource error = new ErrorResource(e.getCode(), message);
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);
  return handleExceptionInternal(e, error, headers, HttpStatus.FORBIDDEN,
      request);
}
 
Example 29
Project: k-framework   File: DefaultApiExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(ConstraintViolationException.class)
@ResponseBody
public ErrorRes constraintViolationExceptionHandler(HttpServletResponse response, ConstraintViolationException e) {
    response.setStatus(400);
    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    if (!violations.isEmpty()) {
        ConstraintViolation<?> violation = violations.iterator().next();
        return new ErrorRes(-1, violation.getPropertyPath().toString() + violation.getMessage());
    }
    return new ErrorRes();
}
 
Example 30
Project: AntiSocial-Platform   File: ExceptionController.java   Source Code and License 5 votes vote down vote up
/**
 * Exception Controller.
 * Catches various exceptions thrown throughout the application runtime.
 *
 * @author Ant Kaynak - Github/Exercon
 */

@ExceptionHandler(NoHandlerFoundException.class)
public String handleError404(Exception e , RedirectAttributes attr)   {
    e.printStackTrace();
        attr.addFlashAttribute("error","Requested page does not exist!");
        return "redirect:/oups";
}
 
Example 31
Project: filter-sort-jooq-api   File: ExceptionTranslator.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(BadUsageApiException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorVM processBadUsageApiError(BadUsageApiException ex) {
    // See jHipster for ErrorVM
    return new ErrorVM(ErrorConstants.ERR_API_BAD_USAGE, ex.getMessage());
}
 
Example 32
Project: Spring-Security-Third-Edition   File: ErrorController.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String exception(final Throwable throwable, final Model model) {
    logger.error("Exception during execution of SpringSecurity application", throwable);
    String errorMessage = (throwable != null ? throwable.getMessage() : "Unknown error");
    model.addAttribute("error", errorMessage);
    return "error";
}
 
Example 33
Project: sentry   File: ExceptionTranslator.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(AccessDeniedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public ErrorVM processAccessDeniedException(AccessDeniedException e) {
    return new ErrorVM(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage());
}
 
Example 34
Project: springboot-learning-example   File: GlobalErrorInfoHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(value = GlobalErrorInfoException.class)
public ResultBody errorHandlerOverJson(HttpServletRequest request,
                                       GlobalErrorInfoException exception) {
    ErrorInfoInterface errorInfo = exception.getErrorInfo();
    ResultBody result = new ResultBody(errorInfo);
    return result;
}
 
Example 35
Project: jkes   File: EndpointAdvice.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(value = { SearchException.class, RuntimeException.class })
@ResponseBody
ResponseEntity<?> handleException(HttpServletRequest request, Throwable ex) {
    HttpStatus status = getStatus(request);
    return new ResponseEntity<>(new EndpointError(status.value(), ex.getMessage()), status);
}
 
Example 36
Project: java-spring-web   File: TestController.java   Source Code and License 5 votes vote down vote up
@ResponseStatus(value = HttpStatus.CONFLICT, reason = "Data integrity violation")
@ExceptionHandler(MappedException.class)
public void mappedExceptionHandler(MappedException ex) {
    verifyActiveSpan();

    // Nothing to do
}
 
Example 37
Project: scalable-task-scheduler   File: ControllerExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler({InternalServerException.class})
@ResponseBody
public ExceptionResponse handleInternalServerException(InternalServerException ex, HttpServletRequest request,
                                                       HttpServletResponse httpResponse) {
    log.error("Internal Server Exception occurred :", ex);
    ExceptionResponse exception = new ExceptionResponse();
    exception.setCode(ex.getErrCode());
    exception.setMessage(ex.getErrMessage());
    httpResponse.setStatus(500);
    return exception;
}
 
Example 38
Project: klask-io   File: ExceptionTranslator.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseBody
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
public ErrorDTO processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) {
    return new ErrorDTO(ErrorConstants.ERR_METHOD_NOT_SUPPORTED, exception.getMessage());
}
 
Example 39
Project: graphium   File: GlobalExceptionController.java   Source Code and License 5 votes vote down vote up
@ResponseStatus(value = HttpStatus.BAD_GATEWAY, reason = "Satellite Graphiums could not be notified")
@ExceptionHandler(NotificationException.class)
public void handleNotificationException(NotificationException ex) {
    log.error("Error occured during request",ex);
}
 
Example 40
Project: sweiproject-tg2b-1   File: ExceptionController.java   Source Code and License 5 votes vote down vote up
/**
 * Dealing a thrown exception {@link InvalidOldPasswordException}.
 *
 * @param exception thrown {@link InvalidOldPasswordException}.
 * @param request   from the client.
 * @return a handle exception internal.
 */
@ExceptionHandler(InvalidOldPasswordException.class)
public ResponseEntity<Object> handleInvalidOldPassword(InvalidOldPasswordException exception, WebRequest request) {
    logger.error(CLIENT_ERROR, exception);
    final GenericResponse bodyOfResponse = new GenericResponse(message.getMessage("message.invalidOldPassword",
            null, request.getLocale()), "InvalidOldPassword");
    return handleExceptionInternal(exception, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
 
Example 41
Project: sweiproject-tg2b-1   File: ExceptionController.java   Source Code and License 5 votes vote down vote up
/**
 * Dealing a thrown exception {@link AccountUserNotFoundException}.
 *
 * @param exception thrown {@link AccountUserNotFoundException}.
 * @param request   from the client.
 * @return a handle exception internal.
 */
@ExceptionHandler(AccountUserNotFoundException.class)
public ResponseEntity<Object> handleAccountUserNotFound(AccountUserNotFoundException exception, WebRequest request) {
    logger.error("404 Status Code", exception);
    final GenericResponse bodyOfResponse = new GenericResponse(message.getMessage("message.accountUserNotFound",
            null, request.getLocale()), "AccountUserNotFound");
    return handleExceptionInternal(exception, bodyOfResponse, new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
 
Example 42
Project: yum   File: ExceptionControllerAdvice.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(value = { Exception.class })
protected ResponseEntity<Object> handleException(Exception ex) {

    StringWriter sw = new StringWriter();
    ex.printStackTrace(new PrintWriter(sw)); 

    LOGGER.log(Level.WARNING, "500 Exception" + "\n" + sw.toString(),""); 
    ex.printStackTrace();
    Error e = new Error();
    e.setError("500");
    e.setMessage("Internal Server Error");
    return new ResponseEntity<>(e,HttpStatus.INTERNAL_SERVER_ERROR);
}
 
Example 43
Project: ingest-core   File: GlobalStateExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ResponseStatus(HttpStatus.CONFLICT)
@ExceptionHandler(InvalidMetadataDocumentStateException.class)
public @ResponseBody
ExceptionInfo handleInvalidMetadataDocumentState(HttpServletRequest request, Exception e) {
    getLog().warn(String.format("Attempt a failed metadata document state transition at '%s'; " +
                    "this will generate a CONFLICT RESPONSE",
            request.getRequestURL().toString()));
    getLog().debug("Handling InvalidMetadataDocumentStateException and returning CONFLICT response", e);
    return new ExceptionInfo(request.getRequestURL().toString(), e.getLocalizedMessage());
}
 
Example 44
Project: loc-framework   File: LocAdviceErrorAutoConfiguration.java   Source Code and License 5 votes vote down vote up
@ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public BasicResult handleHttpMediaTypeNotSupportedException(
    HttpMediaTypeNotSupportedException e) {
  logError("httpMediaTypeNotSupportedException", e.getMessage(), e);
  return BasicResult
      .fail(BasicResultCode.UNSUPPORTED_MEDIA_TYPE_ERROR.getCode(),
          BasicResultCode.UNSUPPORTED_MEDIA_TYPE_ERROR.getMsg(),
          String.format("媒体类型%s错误", e.getContentType()));
}
 
Example 45
Project: scalable-task-scheduler   File: ControllerExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler({RuntimeException.class})
@ResponseBody
public ExceptionResponse handleRuntimeException(RuntimeException ex, HttpServletRequest request,
                                                HttpServletResponse httpResponse) {
    log.error("Runtime exception occurred :", ex);
    ExceptionResponse exception = new ExceptionResponse();
    exception.setCode(CommonExceptionCodes.INTERNAL_SERVER_EXCEPTION.code());
    exception.setMessage(CommonExceptionCodes.INTERNAL_SERVER_EXCEPTION.message());
    httpResponse.setStatus(500);
    return exception;
}
 
Example 46
Project: data-migration   File: HttpExceptionAdvice.java   Source Code and License 5 votes vote down vote up
/**
 * 400 - Bad Request
 */
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public Response handleServiceException(ConstraintViolationException e) {
    log.error("参数验证失败: {}", e);
    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    ConstraintViolation<?> violation = violations.iterator().next();
    String message = violation.getMessage();
    return new Response().failure("parameter:" + message);
}
 
Example 47
Project: renren-fast   File: RRExceptionHandler.java   Source Code and License 5 votes vote down vote up
/**
 * 自定义异常
 */
@ExceptionHandler(RRException.class)
public R handleRRException(RRException e){
	R r = new R();
	r.put("code", e.getCode());
	r.put("msg", e.getMessage());

	return r;
}
 
Example 48
Project: webcron   File: ExceptionResource.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(AssertionError.class)
@ResponseStatus(value = HttpStatus.PRECONDITION_FAILED)
@ResponseBody
public ExceptionDTO handleException(AssertionError e) {
    return handleGenericException(e, HttpStatus.PRECONDITION_FAILED);
}
 
Example 49
Project: logistimo-web-service   File: ErrorHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler({UnauthorizedException.class})
protected ResponseEntity<Object> handleUnauthorizedRequest(RuntimeException e,
                                                           WebRequest request) {
  logWarning(request, e);
  String message = e.getMessage();
  if (StringUtils.isBlank(message)) {
    message = ExceptionUtils.constructMessage("G002",
        getLocale(), null);
  }
  ErrorResource error = new ErrorResource("[Unauthorized]", message);
  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_JSON);
  return handleExceptionInternal(e, error, headers, ((UnauthorizedException) e).getCode(),
      request);
}
 
Example 50
Project: miaohu   File: GlobalExceptionAdvice.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(MultipartException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String,String> uploadErrorHandler(MultipartException e) throws Exception {
    Map message = new HashMap();
    if (e.getCause().getMessage().contains("org.apache.tomcat.common.http.fileupload.FileUploadBase$FileSizeLimitExceededException")){
        message.put("error","文件大小不应该超过" + maxSize);
    }else{
        message.put("error","文件上传错误");
    }
    return message;
}
 
Example 51
Project: plumdo-work   File: GlobalExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(ObjectNotFoundException.class)
@ResponseBody
public ErrorInfo handleNotFound(ObjectNotFoundException e) {
	LOGGER.error("not found object", e);
	return new ErrorInfo("not found object", e);
}
 
Example 52
Project: devops-cstack   File: RestHandlerException.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(value = {OutOfMemoryError.class})
protected ResponseEntity<Object> handleOutOfMemoryError(Exception ex,
                                                        WebRequest request) {
    ex.printStackTrace();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return handleExceptionInternal(
        ex,
        new HttpErrorServer(
            "An unkown error has occured! Server response : OutOfMemoryError"),
        headers, HttpStatus.INTERNAL_SERVER_ERROR, request);
}
 
Example 53
Project: ticket-booking-back-end   File: GlobalExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(NotAcceptableException.class)
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
@ResponseBody
public String unanthorized(NotAcceptableException e) {
    return e.toString();
}
 
Example 54
Project: configcenter   File: GlobalExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(Exception.class)
public AbstractResult handleException(Exception e) {
    logger.error("web层发生异常:", e);

    EmptyResult result = new EmptyResult();
    result.setStatus(Status.PROCESSING);
    result.setCode(CommonResultCode.UNKNOWN_ERROR.getCode());
    result.setMessage(e.getMessage());

    return result;
}
 
Example 55
Project: QuizZz   File: WebExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(UnauthorizedActionException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView unauthorizedAction(HttpServletRequest req, Exception ex) {
	return setModelAndView(req.getRequestURL().toString(), ex, HttpStatus.UNAUTHORIZED.value());
}
 
Example 56
Project: Spring-Shiro-Spark   File: GlobalExceptionHandler.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(value = {ResultException.class})
public ResponseEntity<Object> handleException(ResultException ex, HttpServletRequest request) throws URISyntaxException {
    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(new URI(request.getRequestURI()));
    headers.setContentType(MediaType.APPLICATION_JSON);
    logger.error("-----exception Handler---Host: {} invokes url: {} ERROR: {} Cause:",request.getRemoteHost(),request.getRequestURL(), ex.getMessage(),ex.getCause());
    return handleExceptionInternal(ex,headers,HttpStatus.INTERNAL_SERVER_ERROR,request);
}
 
Example 57
Project: csap-core   File: ErrorHandling.java   Source Code and License 5 votes vote down vote up
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Exception during processing, examine server Logs")
@ExceptionHandler(JsonParseException.class)
public void handleJsonParsing(HttpServletRequest request,Exception e) {
	logger.warn( "{}: {}", request.getRequestURI(),CSAP.getCsapFilteredStackTrace( e ));
	logger.debug( "Full exception", e );
}
 
Example 58
Project: xm-commons   File: ExceptionTranslator.java   Source Code and License 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorVM processValidationError(MethodArgumentNotValidException ex) {
    BindingResult result = ex.getBindingResult();
    FieldErrorVM dto = new FieldErrorVM(ErrorConstants.ERR_VALIDATION, translate(ErrorConstants.ERR_VALIDATION));
    for (FieldError fieldError : result.getFieldErrors()) {
        dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode());
    }
    for (ObjectError globalError : result.getGlobalErrors()) {
        dto.add(globalError.getObjectName(), globalError.getObjectName(), globalError.getCode());
    }
    return dto;
}
 
Example 59
Project: product-management-system   File: ExceptionControllerAdvice.java   Source Code and License 4 votes vote down vote up
/**
 * Handle expired token exception.
 */
@ExceptionHandler(ExpiredJwtException.class)
public ResponseEntity handleExpiredJwtException(final ExpiredJwtException e) {
    log.warn(e.getLocalizedMessage());
    return new ResponseEntity<>(new ErrorDto(e.getLocalizedMessage()), HttpStatus.FORBIDDEN);
}
 
Example 60
Project: tokamak   File: Endpoint.java   Source Code and License 4 votes vote down vote up
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY)
@ExceptionHandler(UnprocessableEntityException.class)
public ErrorsRepresentation handleUnprocessableEntity(UnprocessableEntityException exception, HttpServletRequest request) {
	return convert(exception);
}