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);
}