简体   繁体   English

Spring RestTemplate:在配置类中设置时覆盖ResponseErrorHandler不起作用

[英]Spring RestTemplate : Overridding ResponseErrorHandler not working when set in Configuration class

I have the RestTemplate where l am overridding the ResponseErrorHandler like in the code below我有 RestTemplate,我在下面的代码中覆盖了 ResponseErrorHandler

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
    restTemplate.setErrorHandler(new RsponseError());
    return restTemplate;
}

and my ResponseError class is like this我的 ResponseError 类是这样的

public class RsponseError implements ResponseErrorHandler{

@Override
public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException {
    log.info("statuscode {}",clientHttpResponse.getStatusCode());
    return true;
}

@Override
public void handleError(ClientHttpResponse clientHttpResponse) throws IOException {

    log.info("status code {}",clientHttpResponse.getStatusCode());
    log.info("status text {}",clientHttpResponse.getStatusText());

}

If l autowire the RestTemplate and invoke a rest service and an error is generated the ResponseError does not work.如果我自动装配 RestTemplate 并调用休息服务并生成错误,则 ResponseError 不起作用。 But if l do not set the error handler in the Configuration and set it after autowiring the RestTemplate like below class it will work.但是如果我没有在配置中设置错误处理程序并在像下面的类那样自动装配 RestTemplate 之后设置它,它将起作用。

@Autowired
private RestTemplate restTemplate;


@Override
public ResponseEntity<ClassExampleResponse> invoker(ClassExample classExample,
                                                                String uri) throws Exception {
        final RequestEntity<ClassExample> requestEntity = new RequestEntity<>(classExample, requestHeader(), HttpMethod.POST, new URI("https://somelink"));
        restTemplate.setErrorHandler(new RsponseError());
        final ResponseEntity<ClassExampleResponse> responseEntity = restTemplate.exchange(requestEntity, ClassExampleResponse.class);
    return responseEntity;
}

Why is it that restTemplate.setErrorHandler(new RsponseError());为什么是restTemplate.setErrorHandler(new RsponseError()); is not working when set in configuration class?.在配置类中设置时不起作用?。 Thanks for you help in advance.感谢您提前提供帮助。

You can use @ControllerAdvice to make all your problems disappear!您可以使用@ControllerAdvice让您的所有问题消失!

Here is a short example, which should solves your issue.这是一个简短的示例,它应该可以解决您的问题。 It take the output from your bean validation and display it as JSON.它从您的 bean 验证中获取输出并将其显示为 JSON。

You can take a look at one of my previous answers.你可以看看我之前的一个回答。 This will cover some of the details how this works.这将涵盖其工作原理的一些细节。 Bean validation in DropWizard with custom Json output 带有自定义 Json 输出的 DropWizard 中的 Bean 验证

@ExceptionHandler(MethodArgumentNotValidException.class)
@Order(1)
public ResponseEntity<ValidationErrors> handleUnexpectedException(MethodArgumentNotValidException errors) {

    ValidationErrors validationErrors = new ValidationErrors();

    for (FieldError fe : errors.getBindingResult().getFieldErrors()) {

        String field = fe.getField();
        String msg = fe.getDefaultMessage();

        validationErrors.add(field, msg);
    }
    return new ResponseEntity<ValidationErrors>(validationErrors, HttpStatus.UNPROCESSABLE_ENTITY);
}

public class ValidationErrors {

    public List<ValidationObject> errors = new ArrayList<ValidationObject>();

    public void add(String field, String error){
        errors.add(new ValidationObject(field, error));
    }
}


public class ValidationObject {

    private String field, error;

    public ValidationObject(String field, String error){
        this.field = field;
        this.error = error;
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }
}

I believe the ErrorHandler of your RestTemplate bean is set from other places after RestTemplate bean is generated so that you have to override the ErrorHandler forcely when calling the resttemplate.我相信您的 RestTemplate bean 的 ErrorHandler 是在生成 RestTemplate bean 后从其他地方设置的,因此您必须在调用 resttemplate 时强制覆盖 ErrorHandler。

Please check all the places autowiring the RestTemplate and see if restTemplate.请检查所有自动装配 RestTemplate 的地方,看看 restTemplate. setErrorHandler() is called. setErrorHandler() 被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM