如何将API异常输出传递给自己的REST服务?

时间:2019-07-01 08:52:27

标签: java rest exception resttemplate oauth2resttemplate

摘要: 我想使用自己的Rest服务将一个REST服务端点给出的有效异常输出传递给最终用户。

我所做的是,我已经使用RestTemplate类在服务类中调用了该服务,它会根据有效的发布请求提供有效的输出。但是,当我向其传递无效输入时,在我调用该API的服务类中仅得到“ 400错误请求”结果。但是,当我使用邮递员分别调用该API时,就会得到预期的输出。

代码示例:

class Abc {
    ResponseEntity<String> = response;
    static final String url = "https://abc-xyz.com/client-rest-end-point-url";
    public ResponseEntity getDetails(RequestInput requestInput) {

        try{
            response=restTemplate.postForObject(url,requestInput,String.class);
        } catch(Exception e) {
            ResponseEntity response = (ResponseEntity<ErrorModel>)restTemplate.postForEntity(url,requestInput,ErrorModel.class);
        }//try-catch
    }//getDetails method
}//class

2 个答案:

答案 0 :(得分:0)

使用@ExceptionHandler注释对方法进行注释。您可以在控制器的单独类中进行编码。

@ControllerAdvice
public class YourExceptionHandler {

@ExceptionHandler(CustomException.class)
public String xException() {
 return "error/exception";
}
}

答案 1 :(得分:0)

您可以为整个应用程序创建自定义异常类,并且可以使用JSON关键字在throw中发送数据 假设您有异常类:

public class TestException extends Exception {

private static final long serialVersionUID = 1L;
private String code;
private String detailMessage;

public TestException() {
};

public TestException(String message, String code, String detailMessage) {
    super(message);
    this.code = code;
    this.detailMessage = detailMessage;
}

public TestException(String message, String code) {
    super(message);
    this.code = code;
}
//TestExceptionResponseCode is another class for message data, if required.
public TestException(TestExceptionResponseCode testExceptionResponseCode) {
    super(testExceptionResponseCode.getMessage());
    this.code = testExceptionResponseCode.getCode();
}

public String getCode() {
    return code;
}

public void setCode(String code) {
    this.code = code;
}

public String getDetailMessage() {
    return detailMessage;
}

public void setDetailMessage(String detailMessage) {
    this.detailMessage = detailMessage;
}

}

现在,在您的情况下,抛出异常可能类似于:

class Abc {
ResponseEntity<String> = response;
static final String url = "https://abc-xyz.com/client-rest-end-point-url";
public ResponseEntity getDetails(RequestInput requestInput) {
       if(requestInput==null){
          throw new TestException("FAILED", "1", "Data can't be null");
    }

}