import javax.servlet.ServletResponse; //導入方法依賴的package包/類
public void handleFirstRequest(final HttpServerExchange exchange, final ServletChain servletChain, final ServletRequestContext servletRequestContext, final ServletRequest request, final ServletResponse response) throws Exception {
ThreadSetupAction.Handle handle = setupAction.setup(exchange);
try {
servletRequestContext.setRunningInsideHandler(true);
try {
listeners.requestInitialized(request);
next.handleRequest(exchange);
//
if(servletRequestContext.getErrorCode() > 0) {
servletRequestContext.getOriginalResponse().doErrorDispatch(servletRequestContext.getErrorCode(), servletRequestContext.getErrorMessage());
}
} catch (Throwable t) {
//by default this will just log the exception
boolean handled = exceptionHandler.handleThrowable(exchange, request, response, t);
if(handled) {
exchange.endExchange();
} else if (request.isAsyncStarted() || request.getDispatcherType() == DispatcherType.ASYNC) {
exchange.unDispatch();
servletRequestContext.getOriginalRequest().getAsyncContextInternal().handleError(t);
} else {
if (!exchange.isResponseStarted()) {
response.reset(); //reset the response
exchange.setResponseCode(StatusCodes.INTERNAL_SERVER_ERROR);
exchange.getResponseHeaders().clear();
String location = servletContext.getDeployment().getErrorPages().getErrorLocation(t);
if (location == null) {
location = servletContext.getDeployment().getErrorPages().getErrorLocation(StatusCodes.INTERNAL_SERVER_ERROR);
}
if (location != null) {
RequestDispatcherImpl dispatcher = new RequestDispatcherImpl(location, servletContext);
try {
dispatcher.error(servletRequestContext, request, response, servletChain.getManagedServlet().getServletInfo().getName(), t);
} catch (Exception e) {
UndertowLogger.REQUEST_LOGGER.exceptionGeneratingErrorPage(e, location);
}
} else {
if (servletRequestContext.displayStackTraces()) {
ServletDebugPageHandler.handleRequest(exchange, servletRequestContext, t);
} else {
servletRequestContext.getOriginalResponse().doErrorDispatch(StatusCodes.INTERNAL_SERVER_ERROR, StatusCodes.INTERNAL_SERVER_ERROR_STRING);
}
}
}
}
} finally {
servletRequestContext.setRunningInsideHandler(false);
listeners.requestDestroyed(request);
}
//if it is not dispatched and is not a mock request
if (!exchange.isDispatched() && !(exchange.getConnection() instanceof MockServerConnection)) {
servletRequestContext.getOriginalResponse().responseDone();
servletRequestContext.getOriginalRequest().clearAttributes();
}
if(!exchange.isDispatched()) {
AsyncContextImpl ctx = servletRequestContext.getOriginalRequest().getAsyncContextInternal();
if(ctx != null) {
ctx.complete();
}
}
} finally {
handle.tearDown();
}
}