All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.undertow.server.handlers.ExceptionHandler Maven / Gradle / Ivy

Go to download

This artifact provides a single jar that contains all classes required to use remote EJB and JMS, including all dependencies. It is intended for use by those not using maven, maven users should just import the EJB and JMS BOM's instead (shaded JAR's cause lots of problems with maven, as it is very easy to inadvertently end up with different versions on classes on the class path).

There is a newer version: 34.0.0.Final
Show newest version
package io.undertow.server.handlers;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.AttachmentKey;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Handler that dispatches to a given handler and allows mapping exceptions
 * to be handled by additional handlers.  The order the exception handlers are
 * added is important because of inheritance.  Add all child classes before their
 * parents in order to use different handlers.
 */
public class ExceptionHandler implements HttpHandler {
    public static final AttachmentKey THROWABLE = AttachmentKey.create(Throwable.class);

    private final HttpHandler handler;
    private final List> exceptionHandlers = new CopyOnWriteArrayList<>();

    public ExceptionHandler(HttpHandler handler) {
        this.handler = handler;
    }

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        try {
            handler.handleRequest(exchange);
        } catch (Throwable throwable) {
            for (ExceptionHandlerHolder holder : exceptionHandlers) {
                if (holder.getClazz().isInstance(throwable)) {
                    exchange.putAttachment(THROWABLE, throwable);
                    holder.getHandler().handleRequest(exchange);
                    return;
                }
            }
            throw throwable;
        }
    }

    public  ExceptionHandler addExceptionHandler(Class clazz, HttpHandler handler) {
        exceptionHandlers.add(new ExceptionHandlerHolder<>(clazz, handler));
        return this;
    }

    private static class ExceptionHandlerHolder {
        private final Class clazz;
        private final HttpHandler handler;
        ExceptionHandlerHolder(Class clazz, HttpHandler handler) {
            super();
            this.clazz = clazz;
            this.handler = handler;
        }
        public Class getClazz() {
            return clazz;
        }
        public HttpHandler getHandler() {
            return handler;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy