如何从阿卡演员抛出异常?

问题描述 投票:0回答:1

我有我试图用阿卡集成弹簧启动应用程序。对于大多数我依靠端点上的弹簧启动的建于RuntimeException的机制,但阿卡演员不允许抛出异常有什么想法?

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

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

我有一个调用此方法的演员,我想重新抛出异常正确的,当它发生(我知道一个演员的生命周期不能被打破)

我的异常都是这样的:

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

在我的演员我有这样的方法:

@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格式春季启动除外):

{
    "timestamp": "2019-02-06T06:42:26.740+0000",
    "status": 404,
    "error": "Not Found",
    "message": "user not found",
    "path": "/xxxx/yyy/ssss"
}
java spring akka
1个回答
2
投票

这是可能Exceptions通过传递问格局。这在阿卡文档的ask-send-and-receive-future部分中描述。

综上所述,receive方法中捕获异常,与Failure包装它,并将其发送给发件人。

try {
  String result = operation();
  getSender().tell(result, getSelf());
} catch (Exception e) {
  getSender().tell(new akka.actor.Status.Failure(e), getSelf());
  throw e;
}
© www.soinside.com 2019 - 2024. All rights reserved.