Java Code Examples for org.springframework.http.HttpStatus#is5xxServerError()

The following examples show how to use org.springframework.http.HttpStatus#is5xxServerError() . 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: WebMessageService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
public void send( WebMessage webMessage, HttpServletResponse response, HttpServletRequest request )
{
    String type = request.getHeader( "Accept" );
    type = !StringUtils.isEmpty( type ) ? type : request.getContentType();
    type = !StringUtils.isEmpty( type ) ? type : MediaType.APPLICATION_JSON_VALUE;
    HttpStatus httpStatus = HttpStatus.valueOf( webMessage.getHttpStatusCode() );

    if ( httpStatus.is4xxClientError() || httpStatus.is5xxServerError() )
    {
        response.setHeader( "Cache-Control", CacheControl.noCache().cachePrivate().getHeaderValue() );
    }

    // allow type to be overridden by path extension
    if ( request.getPathInfo().endsWith( ".json" ) )
    {
        type = MediaType.APPLICATION_JSON_VALUE;
    }
    else if ( request.getPathInfo().endsWith( ".xml" ) )
    {
        type = MediaType.APPLICATION_XML_VALUE;
    }

    if ( isCompatibleWith( type, MediaType.APPLICATION_JSON ) )
    {
        sendJson( webMessage, response );
    }
    else if ( isCompatibleWith( type, MediaType.APPLICATION_XML ) )
    {
        sendXml( webMessage, response );
    }
    else
    {
        sendJson( webMessage, response ); // default to json
    }
}
 
Example 2
Source File: GenericExceptionHandlers.java    From kork with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(Exception.class)
public void handleException(Exception e, HttpServletResponse response, HttpServletRequest request)
    throws IOException {
  storeException(request, response, e);

  ResponseStatus responseStatus =
      AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class);

  if (responseStatus != null) {
    HttpStatus httpStatus = responseStatus.value();
    if (httpStatus.is5xxServerError()) {
      logger.error(httpStatus.getReasonPhrase(), e);
    } else if (httpStatus != HttpStatus.NOT_FOUND) {
      logger.error(httpStatus.getReasonPhrase() + ": " + e.toString());
    }

    String message = e.getMessage();
    if (message == null || message.trim().isEmpty()) {
      message = responseStatus.reason();
    }
    response.sendError(httpStatus.value(), message);
  } else {
    logger.error("Internal Server Error", e);
    response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
  }
}
 
Example 3
Source File: RestExceptionHandler.java    From jakduk-api with MIT License 6 votes vote down vote up
@ExceptionHandler(ServiceException.class)
    @ResponseBody
    public ResponseEntity<RestErrorResponse> serviceException(ServiceException ex) {
        ServiceError serviceError = ex.getServiceError();
        HttpStatus httpStatus = HttpStatus.valueOf(serviceError.getHttpStatus());

        RestErrorResponse restErrorResponse = new RestErrorResponse(serviceError, ex.getLocalizedMessage());

        String logMessage;

        try {
            logMessage = ObjectMapperUtils.writeValueAsString(restErrorResponse);
        } catch (JsonProcessingException e) {
            logMessage = "code : " + ex.getServiceError().getCode() + ", message : " + ex.getLocalizedMessage();
        }

        if (serviceError.equals(ServiceError.ANONYMOUS)) {
//            log.info(logMessage);
        } else if (httpStatus.is4xxClientError()) {
            log.warn(logMessage, ex);
        } else if (httpStatus.is5xxServerError()) {
            log.error(logMessage, ex);
        }

        return new ResponseEntity<>(restErrorResponse, HttpStatus.valueOf(serviceError.getHttpStatus()));
    }
 
Example 4
Source File: ApiExceptionRetryPolicy.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean canRetry(RetryContext context) {
    Throwable lastThrowable = context.getLastThrowable();
    if (lastThrowable == null) {
        return true;
    }
    if (lastThrowable instanceof ApiException) {
        if (context.getRetryCount() <= maxAttempts) {
            int code = ((ApiException) lastThrowable).getCode();
            if (code != 0) {
                HttpStatus httpStatus = HttpStatus.valueOf(code);
                boolean httpStatus5xxServerError = httpStatus.is5xxServerError();
                LOGGER.warn("{} Exception occurred during CM API call, retryable: {} ({}/{})",
                        code,
                        httpStatus5xxServerError,
                        context.getRetryCount(),
                        maxAttempts);
                return httpStatus5xxServerError;
            }
        } else {
            return false;
        }
    }
    return false;
}
 
Example 5
Source File: CommonForwardingLogger.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
void logForwardingResult(HttpStatus responseStatus, HttpMethod originalRequestMethod, HttpMethod forwardedRequestMethod, URI originalRequestUri, URI forwardedRequestUri, String mappingName) {
    String logMessage = "Forwarding: {} {} -> '{}' -> {} {} {}";
    if (responseStatus.is5xxServerError()) {
        log(serverErrorLogLevel, logMessage, originalRequestMethod, originalRequestUri, mappingName, forwardedRequestMethod, forwardedRequestUri, responseStatus.value());
    } else if (responseStatus.is4xxClientError()) {
        log(clientErrorLogLevel, logMessage, originalRequestMethod, originalRequestUri, mappingName, forwardedRequestMethod, forwardedRequestUri, responseStatus.value());
    } else {
        log(successLogLevel, logMessage, originalRequestMethod, originalRequestUri, mappingName, forwardedRequestMethod, forwardedRequestUri, responseStatus.value());
    }
}
 
Example 6
Source File: CommonAsynchronousForwarder.java    From charon-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
void logForwardingResult(HttpStatus responseStatus, String mappingName) {
    String logMessage = "Asynchronous execution of '{}' request mapping resulted in {} response status";
    if (responseStatus.is5xxServerError()) {
        log.error(logMessage, mappingName, responseStatus.value());
    } else if (responseStatus.is4xxClientError()) {
        log.info(logMessage, mappingName, responseStatus.value());
    } else {
        log.debug(logMessage, mappingName, responseStatus.value());
    }
}
 
Example 7
Source File: AdviceTraits.java    From problem-spring-web with MIT License 5 votes vote down vote up
public static void log(
        final Throwable throwable,
        final HttpStatus status) {
    if (status.is4xxClientError()) {
        LOG.warn("{}: {}", status.getReasonPhrase(), throwable.getMessage());
    } else if (status.is5xxServerError()) {
        LOG.error(status.getReasonPhrase(), throwable);
    }
}
 
Example 8
Source File: ViewExceptionHandler.java    From jakduk-api with MIT License 5 votes vote down vote up
@ExceptionHandler({ ServiceException.class })
public ModelAndView handleServiceException(HttpServletRequest request, ServiceException exception) {

    ServiceError serviceError = exception.getServiceError();
    HttpStatus httpStatus = HttpStatus.valueOf(serviceError.getHttpStatus());

    RestErrorResponse restErrorResponse = new RestErrorResponse(serviceError, exception.getLocalizedMessage());

    String logMessage;

    try {
        logMessage = ObjectMapperUtils.writeValueAsString(restErrorResponse);
    } catch (JsonProcessingException e) {
        logMessage = "code : " + exception.getServiceError().getCode() + ", message : " + exception.getLocalizedMessage();
    }

    ModelAndView modelAndView = new ModelAndView();

    if (httpStatus.is4xxClientError()) {
        modelAndView.setViewName("error/4xx");
        log.warn(logMessage, exception);

    } else if (httpStatus.is5xxServerError()) {
        modelAndView.setViewName("error/" + httpStatus.toString());
        log.error(logMessage, exception);
    }

    Map<String, Object> map = getErrorAttributes(request, false);
    modelAndView.addAllObjects(map);
    modelAndView.setStatus(httpStatus);
    modelAndView.addObject("status", httpStatus.value());

    return modelAndView;
}
 
Example 9
Source File: CustomResponseErrorHandler.java    From hellokoding-courses with MIT License 4 votes vote down vote up
@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
    HttpStatus status = clientHttpResponse.getStatusCode();
    return status.is4xxClientError() || status.is5xxServerError();
}