2

I am using jersey with spring boot, and I have a exception mapper:

package org.smarter.providers;

import com.google.common.collect.ImmutableMap;
import org.smarter.exception.ApiException;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import java.util.Optional;

import static org.smarter.exception.UserException.UNAUTHORIZED;

@Provider
public class ExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<ApiException> {

    @Override
    public Response toResponse(ApiException exception) {
        return Response.status(status(exception)).build();
    }

    private Integer status(ApiException exception) {
        return Optional.ofNullable(ImmutableMap.<String, Integer>builder()
                .put(UNAUTHORIZED, 401)
                .build()
                .get(exception.code()))
                .orElse(404);
    }
}

Also registered, and using debug, i can see this mapper get invoked correctly, but how ever the final response still returning 404, no matter using junit test or manual test.

Here is the test:

when()
                .get("/users/current/memos/daily")
                .then()
                .statusCode(401);

And then registered in Jersey Configuration:

register(ExceptionMapper.class);

I am using jersey with spring boot, and don't know how to trouble shooting on this. any advice will be appreciated.

Jakim
  • 1,713
  • 7
  • 20
  • 44
  • 1
    Possible duplicate of [Jersey ExceptionMapper doesn't map exceptions](https://stackoverflow.com/questions/27982948/jersey-exceptionmapper-doesnt-map-exceptions) – Ori Marko May 15 '18 at 14:36
  • @user7294900, I already registered as that post suggested, thanks. – Jakim May 19 '18 at 09:52
  • https://stackoverflow.com/questions/36597274/jersey-returns-404-with-any-error-status-code – Jakim May 19 '18 at 09:58

1 Answers1

0

I can see this mapper gets invoked correctly, but how ever the final response still returning 404.

It may be an issue with the implementation of your status() method. Are you sure exception.code() returns 401?

By the way, do you need such level of complexity using an Optional and an ImmutableMap? You could use:

private Integer status(ApiException exception) {
    if (exception.code() == 401) {
        return exception.code();
    } else {
        return 404;
    }
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • the `exception.code()` actually only returns a string which is the my exception code in my application, for example, is the user is unauthorized, it will return `"unauthorized"`, I am tying to build a map between my exception code and http status code, so I use ImmutableMap, which key is the my exception code, and value is the htt p status code, and Optional was used for non-exist mapping. By the way, I can confirm that the exception.code() is returning "UNAUTHORIZED" by evaluate when debugging, and which should correctly map to 401. Thanks for the answer anyway. – Jakim May 19 '18 at 09:50