gpt4 book ai didi

java - 如何从 akka actor 抛出异常?

转载 作者:行者123 更新时间:2023-12-02 01:40:17 24 4
gpt4 key购买 nike

我有一个 Spring Boot 应用程序,我正在尝试将其与 akka 集成。对于大多数端点,我依赖于内置 RuntimeException 机制的 spring boot,但 akka 参与者不允许抛出异常任何想法?

我有这个助手来调用其他服务:

public ResponseEntity<R> callService(String address
, MultiValueMap<String, String> headers
, B body
, HttpMethod httpMethod
, ParameterizedTypeReference<R> parameterizedTypeReference
, ExceptionHandlerCustom exceptionHandlerCustom) {
try {
HttpEntity<B> request = new HttpEntity<>(body, headers);
return restTemplate.exchange(address
, httpMethod
, request
, parameterizedTypeReference);
} catch (Exception e) {
if (e instanceof HttpStatusCodeException) {
HttpStatusCodeException exception = (HttpStatusCodeException) e;
Gson gson = new Gson();
Response<String> errorResponse =
gson.fromJson(exception.getResponseBodyAsString(), new TypeToken<Response<String>>(){}.getType());
if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
throw new BadRequestException(errorResponse.getMessage());
} else if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
throw new UnauthorizedException("not authorized");
} else if (exception.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
e.printStackTrace();
throw new InternalServerErrorException();
} else if (exceptionHandlerCustom != null) {
exceptionHandlerCustom.handle(e);
}else
e.printStackTrace();
}
throw e;
}
}

我有一个调用此方法的 Actor ,我想在异常发生时重新抛出异常(我知道 Actor 的生命周期无法被破坏)

我的异常都是这样的:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
public NotFoundException(String message) {
super(message);
}
}

在我的 Actor 中我有这个方法:

@Override
public Receive createReceive() {
return receiveBuilder()
.match(CheckUserIdAndProvidedToken.class, message -> {
getSender().tell(tokenCheckService.checkUserIdAndProvidedToken(message.getToken()
, message.getId()), getSelf());
})
.build();
}

在服务中我这样调用它:

Future<Object> futureOfCheck = ask(checker, new         
TokenCheckActor.CheckUserIdAndProvidedToken(id, token), timeout);

当异常发生时,我喜欢将其抛出给客户端(json格式的spring boot异常):

{
"timestamp": "2019-02-06T06:42:26.740+0000",
"status": 404,
"error": "Not Found",
"message": "user not found",
"path": "/xxxx/yyy/ssss"
}

最佳答案

可以通过询问模式传递异常。这在ask-send-and-receive-future中有描述。 akka 文档的部分。

总之,在 receive 方法中捕获异常,用 Failure 包装它并将其发送给发送者。

try {
String result = operation();
getSender().tell(result, getSelf());
} catch (Exception e) {
getSender().tell(new akka.actor.Status.Failure(e), getSelf());
throw e;
}

关于java - 如何从 akka actor 抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54547995/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com