如何使用RxJava实现处理错误

时间:2019-01-04 16:01:45

标签: exception-handling rx-java

我想引发异常而不是返回Single。我不确定这是否是正确的方法。我找不到与我的代码类似的RxJava处理错误的示例。这是一个企业应用程序,因此我无法更改太多错误处理。

//这是我的服务

public Observable<MyModel> observe() {
    return movieDetailServiceClientRetrofit
            .getMovieById(idMovie)
    .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.computation())
            .onErrorResumeNext(HANDLE_ERROR)
    .toObservable();

// Currently, I'm returning a Single with the error to my endpoint and from this endpoint I return the error to the client
// What I want to do is to throw an exception, for example NoAuthorizationException and return that custom message to the client
// If I do inside HANDLE_ERROR: 
    throw new NoAuthorizationException(); 
// I get a compilation error: must be caught or declared to be thrown 
// I know that I have to declare like this throws NoAuthorizationException in the signature
// but not sure how to do it as the signature is a CONSTANT HANDLE_ERROR. 

private static final Func1<Throwable, Single<? extends MyModel>> HANDLE_ERROR = throwable -> {
    if (null != throwable.getCause() && throwable.getCause() instanceof HttpException || throwable instanceof HttpException) {
        HttpException exception = throwable instanceof HttpException ? (HttpException) throwable : (HttpException) throwable.getCause();
        System.out.println("Llega hasta aca - Exception code: " + exception.code());
        if (BAD_REQUEST.value() == exception.code()) {
    // How can I throw an exception here instead of returning a Single?
            return Single
                    .error(throwable);
        } else if (NOT_FOUND.value() == exception.code()) {
    // How can I throw an exception here instead of returning a Single?
            return Single
                    .error(throwable);
        } else if (FORBIDDEN.value() == exception.code()) {
    // How can I throw an exception here instead of returning a Single?
            return Single
                    .error(throwable);
        } else if (UNAUTHORIZED.value() == exception.code()) {
    // How can I throw an exception here instead of returning a Single?
            return Single
        .error(throwable);
        }
    }
// How can I throw an exception here instead of returning a Single?
    return Single.error(throwable.getCause());
};

//这是我的ExceptionHandler

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(NoAuthorizationException.class)
    protected ResponseEntity<Object> handleNoAuthorization(NoAuthorizationException ex) {
        ApiError apiError = new ApiError(HttpStatus.UNAUTHORIZED, ex.getMessage(), ex);
        return buildResponseEntity(apiError);
    }
}

您能帮上忙吗?谢谢

0 个答案:

没有答案