Reputation: 744
I'm doing a Webservice in java using Jersey. my dependencies for jersey are:
/* JAX-RS Impl (Jersey) */
compile 'org.glassfish.jersey.inject:jersey-hk2:2.27'
compile 'org.glassfish.jersey.containers:jersey-container-servlet:2.27'
compile 'org.glassfish.jersey.media:jersey-media-sse:2.27'
compile 'org.glassfish.jersey.core:jersey-server:2.27'
//Jackson implementation
compile 'org.glassfish.jersey.media:jersey-media-json-jackson:2.27'
// Hateoas
compile 'org.glassfish.jersey.ext:jersey-declarative-linking:2.27'
//Jersey Impl test
compile 'org.glassfish.jersey.test-framework:jersey-test-framework-core:2.27'
compileOnly 'javax.servlet:javax.servlet-api:4.0.1'
My class Exception looks like the next snippet, I'm catching all Throwable to test this works.
package com.apporelbotna.appuestas.rest.exception;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class WebserviceExceptionMapper implements ExceptionMapper<Throwable>
{
public WebserviceExceptionMapper()
{
System.out.println("I'm getting created!!! - WebserviceExceptionMapper");
}
public Response toResponse(Throwable ex)
{
return Response.status(404).build();
}
}
And my rest Endpoint looks like:
@GET
public Response getUsers() throws Exception
{
throw new Exception("Hi i'm crashing!");
}
I read the documentation of Jersey and i undestand that i can register the exception mappers using @provider in the class. But the application doesn't recognize the class. I tried to register my class in my ResourceConfig class. And this it works.
@Provider
@javax.ws.rs.ApplicationPath("webservice")
public class RestResourceConfig extends ResourceConfig
{
@Context
public void setServletContext(ServletContext context)
{
if (context != null)
{
context.getInitParameter("system.info.allow");
}
}
public RestResourceConfig()
{
// Register components in a package
register(WebserviceExceptionMapper.class);
packages("com.apporelbotna.appuestas.rest.endpoint");
}
}
What i'm missing?
Upvotes: 1
Views: 2728
Reputation: 208984
packages("com.apporelbotna.appuestas.rest.endpoint")
This tells Jersey which package(s) to scan for @Provider
and @Path
classes and register them. You can list multiple packages or you can just use a base package like com.apporelbotna.appuestas
and Jersey will scan the package recursively.
So if you want your ExceptionMapper
to be registered automatically, do one of the following
packages("com.apporelbotna.appuestas.rest.endpoint",
"com.apporelbotna.appuestas.rest.exception");
// -or-
packages("com.apporelbotna.appuestas.rest");
Upvotes: 2