How to pass API exception output to through own RE

2019-08-20 06:28发布

问题:

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.

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.

Code sample :

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

回答1:

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");
    }

}



回答2:

Annotate your method with @ExceptionHandler annotation. You can code in seperate class from controller.

@ControllerAdvice
public class YourExceptionHandler {

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