@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; }
@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); }
@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; }
/** * 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); }
@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; }
/** * 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); }
@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); }
/** * 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; }
@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; }
/** * 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; }
@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); }
/** * 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); }
@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())); }
@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"; }
@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()); }
/** * 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()); }
@ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(Throwable.class) public String unknownException(Throwable exception) { log(exception); return messageSourceAccessor.getMessage("error.unknown", new Object[]{exception.getMessage()}); }
/** * 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); }
@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; }
@ExceptionHandler({UnknownSessionException.class}) public ModelAndView processUnknownSessionException(NativeWebRequest request, MissingServletRequestParameterException e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception", e.getMessage()); mv.setViewName("/signin"); return mv; }
@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); }
@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(); }
/** * 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"; }
@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()); }
@ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody public ErrorVM processAccessDeniedException(AccessDeniedException e) { return new ErrorVM(ErrorConstants.ERR_ACCESS_DENIED, e.getMessage()); }
@ExceptionHandler(value = GlobalErrorInfoException.class) public ResultBody errorHandlerOverJson(HttpServletRequest request, GlobalErrorInfoException exception) { ErrorInfoInterface errorInfo = exception.getErrorInfo(); ResultBody result = new ResultBody(errorInfo); return result; }
@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); }
@ResponseStatus(value = HttpStatus.CONFLICT, reason = "Data integrity violation") @ExceptionHandler(MappedException.class) public void mappedExceptionHandler(MappedException ex) { verifyActiveSpan(); // Nothing to do }
@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; }
@ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseBody @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) public ErrorDTO processMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) { return new ErrorDTO(ErrorConstants.ERR_METHOD_NOT_SUPPORTED, exception.getMessage()); }
@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); }
/** * 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); }