Frage

I am new to JAX-RS and still learning it, so my question can be a little naive so please bear with it :)

I have been going through various SO questions for "error codes for http response" . I have found out that as long as one dont want to be pedantic he can return 4xx status codes in the response.

I have also gone through this link RFS 2616 also the W3

I wanted to know is there any general practice to return custom error codes other than standard HTTP response status codes.

e.g if in post request for getting user information by userid and return error if userid is invalid / doesnt exists. In this case HTTP status 422 sounds idle. But if detailed error description is needed can custom error like 40xx where xx is value other than http errors be returned to client.

similarly can 40xx be defined and returned in response to client ? ( having correct syntax in the request )

4001 - userid invalid

4002 - post id invalid

etc..

or should I return 4xx status code and in the response body add by own codes for more error details?

War es hilfreich?

Lösung

If you're developing internal system that won't go public then you can go with custom codes. On the other hand if you want to expose some APIs to public it's better to stick to the standard codes and provide more information in status reason phrase or in entity body.

In JAX-RS you can create your own statuses (or override reason phrases of standard statuses) like:

public static class CustomBadRequestType implements Response.StatusType {

    @Override
    public int getStatusCode() {
        return 400;
    }

    @Override
    public String getReasonPhrase() {
        return "My Reason";
    }

    @Override
    public Response.Status.Family getFamily() {
        return Response.Status.Family.CLIENT_ERROR;
    }
}

and then set the status to the Response.ResponseBuilder:

Response.status(new CustomBadRequestType()).build();

Andere Tipps

One can extend existing interface with more custom codes(and keep existing one's) as below:

public enum CustomResponseStatus implements Response.StatusType {
    OK(Response.Status.OK.getStatusCode(), "OK"),
    CREATED(Response.Status.CREATED.getStatusCode(), "Created"),
    INVALID_INPUTS(419, "Invalid inputs");
}

You can set the CustomResponseStatus codes as part of Response object as below

ResponseBuilder.status(CustomResponseStatus.INVALID_INPUTS).build();

If the custom statuses are between integers 102 and 599 (inclusive), there is also an option to set the status with int value:

ResponseBuilder.status(451).build();

In fact using the standard groupings (1xx,2xx,3xx,4xx,5xx) is highly recommended even with custom status codes. (The examples provided should probably be 4xx Client errors.)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top