如何将API异常输出传递给自己的REST服务? [英] How to pass API exception output to through own REST service?
问题描述
摘要:
我想通过使用我自己的Rest服务将一个REST服务端点给出的有效异常输出传递给最终用户。
Summary : I want to pass valid exception output given by one REST service end point to the end user by using my own Rest service.
什么我所做的是,我已经使用RestTemplate类在服务类中调用了该服务,它在有效的发布请求中提供了有效的输出。但是,当我向其传递无效输入时,在我调用该API的服务类中仅得到 400错误请求结果。但是,当我使用邮递员分别调用该API时,就会得到预期的输出。
What I did is, I have called that service in service class using RestTemplate class, it's giving valid output on valid post request. But when I am passing invalid input to it I am getting only '400 BAD REQUEST' result in my service class where I have called that API. But when I am calling that API separately using postman, there I'm getting expected output.
代码示例:
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
推荐答案
您可以为整个应用程序创建一个自定义的异常类,并且可以通过使用 JSON
发送数据。 code> throw 关键字
假设您具有异常类:
You can create a custom exception class for your entire application and you can send data in JSON
by using throw
keyword
Suppose you have exception class is:
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;
}
}
现在,在您的情况下,抛出异常可以像这样:
Now in your case throwing exception can be like :
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");
}
}
这篇关于如何将API异常输出传递给自己的REST服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!