Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Exception handling components #282

Open
fcamblor opened this issue Sep 18, 2017 · 0 comments
Open

Exception handling components #282

fcamblor opened this issue Sep 18, 2017 · 0 comments

Comments

@fcamblor
Copy link
Contributor

fcamblor commented Sep 18, 2017

This is very frequent that some RestX projects implements a RestxFilter for exception handling, because there is no extension point on StdRestxMainRouter exception handling

I would introduce a new RestxExceptionHandler interface for this purpose :

public interface RestxExceptionHandler<E extends Throwable> extends Predicate<Throwable> {
    void handle(E exception, RestxRequest restxRequest, RestxResponse restxResponse);
}
public abstract class RestxExceptionHandlerBase<E extends Throwable> implements RestxExceptionHandler<E> {
    private Class<E> exceptionClass;
    public RestxExceptionHandlerBase(Class<E> exceptionClass) {
        this.exceptionClass = exceptionClass;
    }

    public boolean apply(Throwable t) {
        return exceptionClass.isAssignableFrom(t);
    }

    // Maybe some more utility methods such as the one for filtering stacktraces (see #281)
}

with a bunch of default exception handlers allowing to replicate existing exception handlings in StdRestxMainRouter, for instance :

@Module(priority = 1000)
public class ErrorsModule {
    @Provide @Named("WebException")
    public RestxExceptionHandler<? extends Throwable> webException() {
        return new RestxExceptionHandlerBase(WebException.class) {
            void handle(WebException ex, RestxRequest restxRequest, RestxResponse restxResponse) {
                ex.writeTo(restxRequest, restxResponse);
            }
        });
    }

    @Provide @Named("RestxException")
    public RestxExceptionHandler<? extends Throwable> webException() {
        return new RestxExceptionHandlerBase(RestxError.RestxException.class) {
            void handle(RestxError.RestxException ex, RestxRequest restxRequest, RestxResponse restxResponse) {
                logger.debug("request raised RestxException", ex);
                restxResponse.setStatus(ex.getErrorStatus());
                restxResponse.setContentType("application/json");
                PrintWriter out = restxResponse.getWriter();
                out.println(ex.toJSON());
            }
        });
    }
    // etc..
}

WDYT ?

@fcamblor fcamblor changed the title Exception handling component Exception handling components Sep 18, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant