作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
摘要:我想使用我自己的 Rest 服务将一个 REST 服务端点给出的有效异常输出传递给最终用户。
我所做的是,我使用 RestTemplate 类在服务类中调用该服务,它在有效的发布请求上提供有效的输出。但是,当我向它传递无效输入时,我在调用该 API 的服务类中仅得到“400 BAD REQUEST”结果。但是,当我使用 postman 单独调用该 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
最佳答案
您可以为整个应用程序创建自定义异常类,并且可以使用 throw
关键字以 JSON
格式发送数据假设您的异常类是:
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");
}
}
关于java - 如何通过自己的REST服务传递API异常输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56832667/
我是一名优秀的程序员,十分优秀!