处理休息模板错误

时间:2018-03-27 14:38:23

标签: java spring

我开发了一个服务,使用resttemplate并在另一个项目(服务器)中使用此服务(clientproject),我试图从resttemplate抛出异常并处理服务器项目,但它无法正常工作。

这是我的代码:

public class UserService{

    public long createUser(Long servcieId){
     long userId =0L;
    try
    {
        response = restTemplate.exchange(url,HttpMethod.POST, request, Object.class);
         userId = response.getBody().getUser().getId();
    }
    catch(RestClientException e){

        throw e;
    }
    return userId;
    }
 }

这是我的服务代码:

public Long createUserInPortal(Long serviceId){

    try
        {
        Long userId=userService.createUser(serviceId);
        }
        catch(RestClientException e){
         if(e instanceof HttpStatusCodeException){
            String errorResponse=((HttpStatusCodeException)e).getResponseBodyAsString();
            logger.error("the error in user service is:"+errorResponse);
        }
}

我收到以下错误,“导致422(不可处理的实体);调用错误处理程序”。 我试图在catch块中看到响应字符串,但它没有到达这个catch块。

1 个答案:

答案 0 :(得分:0)

好吧可能是它进入内部捕获块但是被

过滤掉了

if(e instanceof HttpStatusCodeException){条件

可能是e实例不是HttpStatusCodeException类型还有其他可能性如

    } catch (HttpClientErrorException e) {
        success = false;
        Log.e(TAG, command+" was rejected for URL: "+url, e);
        resultCode = e.getStatusCode().value();
        response = e.getResponseBodyAsString();
    } catch (HttpServerErrorException e) {
        success = false;
        Log.e(TAG, command+" could not be completed for URL: "+url, e);
        resultCode = e.getStatusCode().value();
        response = e.getResponseBodyAsString();
    } catch (ResourceAccessException e) {
        if (attemptsLeft > 0) {
            Log.w(TAG, command+" failed I/O, retrying.", e);
            return simplePut(baseUrl, url, b, command, payload, attemptsLeft);
        }
        success = false;
        Log.e(TAG, command+" failed I/O for URL: "+url, e);
        resultCode = 499;
    } catch (RestClientException e) {
        success = false;
        Log.e(TAG, command+" failed for URL: "+url, e);
        resultCode = 599;
    }
相关问题