spring异常处理:将异常从另一个服务传递给客户机

uqdfh47h  于 2021-07-12  发布在  Java
关注(0)|答案(0)|浏览(269)

我读过很多关于这个主题的帖子,博客和问题,但是我找不到解决问题的方法。这也有可能是我遵循了一个错误的机制,所以请纠正我,如果我错了。
背景:
我正在开发2个测试微服务来学习spring异常处理。所以我使用@controlleradvice和一个定制的exceptionhandler在这两个服务中全局地处理该机制。当异常立即返回到客户机时,这可以正常工作。我定义了一个自定义的errorresponse类,它保存有关statuscode、消息和时间戳的信息。
假设我有服务a和服务b。服务a调用服务b来获取一些数据,这是一个非常常见的例子。在服务b中找不到实体。所以我抛出一个带有特定消息的自定义NotFound异常。在这里,我对@controlleradvice annotatent responseEntityExceptionHandler和自定义errorresponse类使用相同的机制。
问题:现在我计划要么直接将这个异常传递给客户机,要么在服务a中捕获它,执行另一个日志,然后将它作为格式良好的json描述传递。
当我没有用自定义responseEntityExceptionHandler捕获服务a中的excation时,我的response对象中的message字段总是空的,errorcode不是我从服务b抛出的源404。

{
    "timestamp": "2020-08-18T11:30:42.955+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "message": "",
    "path": "/greetings/3"
}

如果在自定义ResponseEntityExceptionHandler中捕获异常,则在httpclienterrorexception中生成以下对象:

{
    "message": "404 : [{\"message\":\"Greeting with id: 3 not found.\",\"httpStatus\":\"NOT_FOUND\",\"timeStamp\":\"2020-08-18T13:59:57.7842091+02:00\"}]",
    "httpStatus": "NOT_FOUND",
    "timeStamp": "2020-08-18T13:59:57.7988487+02:00"
}

因此,我从服务b返回的整个对象在detailmessage中表示为一个串联的字符串。
问题:我认为更好的方法是捕获服务a中的异常,记录它,然后将它与服务b设置的消息一起返回给客户机。这条路对吗?
代码
自定义execeptionhandler服务b:

@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    private final Logger log = Logger.getLogger(this.getClass().getName());

    @ExceptionHandler(GreetingNotFoundException.class)
    protected ResponseEntity<ErrorResponse> handleGreetingNotFoundException(GreetingNotFoundException ex){
        log.severe(ex.getMessage());
        return new ResponseEntity<>(new ErrorResponse(ex.getMessage(),HttpStatus.NOT_FOUND),HttpStatus.NOT_FOUND);
    }
}

使用服务b中抛出的异常的服务a的异常处理程序:

@ControllerAdvice
public class CustomRestTemplateResponseErrorHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(HttpClientErrorException.class)
    protected ResponseEntity<ErrorResponse> handleException(HttpClientErrorException ex ) {
        return new ResponseEntity<>(new ErrorResponse(ex.getMessage(),ex.getStatusCode()),ex.getStatusCode());
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题