简体   繁体   中英

Can't catch 400 Bad Request with javax.ws.rs.ext.ExceptionMapper

I have a REST service method that uses the POST http method and accepts application/json . The JSON is bound to a JAXB bean:

@POST
public void test(final HierResult obj) throws Exception {
    printHierResult(obj);
}

@XmlRootElement
public static class HierResult {
    public String dummy;
}

I noticed that when somebody sends me a syntactically valid JSON containing unknown field, say { "aaa": "bbb" } then no error is logged, but the web server returns:

HTTP/1.1 400 Bad Request
Server: WildFly/11

Unrecognized field "aaa" (class HierResult), not marked as ignorable

So the question is: how do I log this error?

I registered an ExceptionMapper for java.lang.Exception , but it can only catch JsonParseException or the exceptions thrown by my java method, not the error above.

@Provider
public class MyExceptionLogger implements ExceptionMapper<Exception> {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyExceptionLogger.class);
    @Override
    public Response toResponse(final Exception exception1) {
        LOGGER.error("", exception1);
        return Response
            .serverError()
            .status(Response.Status.BAD_REQUEST)
            .entity(String.valueOf(exception1.toString()))
            .build();
    }
}

@javax.ws.rs.ApplicationPath("webresources")
public class ApplicationConfig extends Application {
    @Override
    public Set<Class<?>> getClasses() {
        final Set<Class<?>> resources = new java.util.HashSet<>();
        addRestResourceClasses(resources);
        return resources;
    }
    private void addRestResourceClasses(final Set<Class<?>> resources) {
        resources.add(MyExceptionLogger.class);
    }        
}

As @PaulSamsotha commented, had to register a mapper that has same or more pricise exception class.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <version>2.10.2</version>
  <artifactId>jackson-databind</artifactId>
  <scope>provided</scope>
</dependency>

_

import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException;

public class TestMapper implements ExceptionMapper<UnrecognizedPropertyException> {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestMapper.class);

    @Override
    public Response toResponse(final UnrecognizedPropertyException exception1) {
        LOGGER.error("server side error", exception1);
        return Response
            .serverError()
            .status(Response.Status.INTERNAL_SERVER_ERROR)
            .entity(String.valueOf(Response.Status.INTERNAL_SERVER_ERROR))
            .build();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM