java begineer
java begineer

Reputation: 319

Best practice of handling multiple http status error code in java

What’s the best practice of handling multiple http status error code, For example, I want to handle all 4xx and 5xx status code, except 404.

I’ve my current implementation like below : (I’ve place only sample code)

if ( HTTP.STATUS == 500 || HTTP.STATUS == 502 || HTTP.STATUS == 503  || HTTP.STATUS == 400
      || HTTP.STATUS == 401 || HTTP.STATUS == 402 || HTTP.STATUS == 403) {

String status = “Failed to send”;

}

I know this is very ugly code, can anyone suggest best way of handling the error code between 4xx and 5xx except 404 using java program

Upvotes: 3

Views: 10747

Answers (4)

Shaun O'Hagan
Shaun O'Hagan

Reputation: 311

As you are able to switch on Enums in Java, define an Enum for the range of possible codes e.g.

public enum HttpStatusCodeRange {
SUCCESS_RANGE, CLIENT_ERROR_RANGE, SERVER_ERROR_RANGE, UNKNOWN; }

Then create a utility to calculate the Enum for the particular code you get e.g.

public static HttpStatusCodeRange getRange(int code) {
    if (code >= 200 && code < 300) {
        return HttpStatusCodeRange.SUCCESS_RANGE;
    } 
    if (code >= 400 && code < 500) {
        return HttpStatusCodeRange.CLIENT_ERROR_RANGE;
    } 
    if (code >= 500 && code < 600) {
        return HttpStatusCodeRange.SERVER_ERROR_RANGE;
    } 
    return HttpStatusCodeRange.UNKNOWN;
}

Then you can write fairly neat code to process your HTTP response codes e.g.

    HttpStatusCodeRange range = HttpStatusCodeRangeUtil.getRange(response.getStatus());
    switch (range) {
    case SUCCESS_RANGE :
        handleSuccess();
        break;
    case CLIENT_ERROR_RANGE :
        handleClientError();
        break;  
    case SERVER_ERROR_RANGE :
        handleServerError();
        break;  
    case UNKNOWN :
        handleUnexpectedError();
        break;  
    default :
        handleUnknownError();
        break;
    }

Upvotes: 2

squarewav
squarewav

Reputation: 433

Something like so perhaps:

if (status == 404) {
    // handle 404
} else {
    String sstatus = '' + status;

    switch (sstatus.charAt(0)) {
        case '4':
            // handle 4xx 
            break
        case '5':
            ...

Upvotes: 0

Ian
Ian

Reputation: 1504

This may not be a good solution for HTTP status codes, but with regards to matching many possible values, you can use a switch statement without break to stack them all:

String status = null;
switch (HTTP.STATUS) {
    case 400:
    case 401:
    case 402:
    case 403:
    case 500:
    case 502:
    case 503:
        status = “Failed to send”;
        break;

    default:
        status = "All ok!";
}

Upvotes: 1

m.aibin
m.aibin

Reputation: 3603

It's better to send particular messages, for different HTTP status responses. Look here: http://racksburg.com/choosing-an-http-status-code/

You can also make some generic method like this:

public class GenericExceptionMapper implements ExceptionMapper<Throwable> {

    @Override 
    public Response toResponse(Throwable ex) {

        ErrorMessage errorMessage = new ErrorMessage();     
        setHttpStatus(ex, errorMessage);
        errorMessage.setCode(AppConstants.GENERIC_APP_ERROR_CODE);
        errorMessage.setMessage(ex.getMessage());
        StringWriter errorStackTrace = new StringWriter();
        ex.printStackTrace(new PrintWriter(errorStackTrace));
        errorMessage.setDeveloperMessage(errorStackTrace.toString());
        errorMessage.setLink(AppConstants.BLOG_POST_URL);

        return Response.status(errorMessage.getStatus())
                .entity(errorMessage)
                .type(MediaType.APPLICATION_JSON)
                .build();   
    }

    private void setHttpStatus(Throwable ex, ErrorMessage errorMessage) {
        if(ex instanceof WebApplicationException ) {
            errorMessage.setStatus(((WebApplicationException)ex).getResponse().getStatus());
        } else {
            errorMessage.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); //defaults to internal server error 500
        }
    }
}

Upvotes: 0

Related Questions