简体   繁体   中英

Exception Handling in JAX-RS

java 8, spring, rest

I am trying to capture the Response that comes from exception mapper, and do something with it in the caller which throws the exception. Thanks.

@Provider
public class CustomerExceptionHandler implements ExceptionMapper<CustomerException> 
{
    @Override
    public Response toResponse(CustomerException exception) 
    {
        return Response.status(Status.BAD_REQUEST).entity(CustomerException.getMessage()).build();  
    }
}


public class CustomerException extends Exception implements Serializable
{
    private static final long serialVersionUID = 1L;

    public CustomerException() {
        super();
    }
    public CustomerException(String msg)   {
        super(msg);
    }
    public CustomerException(String msg, Exception e)  {
        super(msg, e);
    }
}



public class ExceptionDemo{

  public void getExceptionResponse(){
      //do something 
      throw new CustomerException("Something is wrong");// CustomerExceptionHandler is going to return me a Response, how can I capture the response here?
      //capture response and do something with it
  }
}

I'm not sure ExceptionMapper s work in the way you think they do.

When some code in the endpoint throws an exception, and this exception percolates all the way out of the endpoint and back into the container itself (Spring in this case), then the registered ExceptionMapper s are consulted to see if they match the thrown exception, and the relevant one's public Response toResponse(T e) {} method is called to transform it into a Response .

The ExceptionMapper doen't get called as part of your endpoint code, and you won't be able to take action based on its resultant Response because it hasn't yet been called. You just need to throw the exception out of the endpoint.

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