JAX-RS中的异常处理

问题描述 投票:0回答:1

java 8,春季,休息

我正在尝试捕获来自异常映射器的Response,并在引发异常的调用方中对其进行处理。谢谢。

@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
  }
}

java spring exception jaxb jax-rs
1个回答
0
投票

我不确定ExceptionMapper的工作方式是否与您认为的一样。

当端点中的某些代码引发异常,并且此异常从端点渗出并再次渗入容器本身(在这种情况下为Spring)时,then请咨询已注册的ExceptionMapper看看它们是否与抛出的异常匹配,然后调用相关人的public Response toResponse(T e) {}方法将其转换为Response

ExceptionMapper不会作为端点代码的一部分被调用,并且您将无法基于其结果Response采取措施,因为尚未调用它。您只需要throw端点之外的异常即可。

© www.soinside.com 2019 - 2024. All rights reserved.