view src/luan/webserver/handlers/SafeHandler.java @ 1138:4189027691b7

webserver - add LogHandler
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 29 Jan 2018 19:48:21 -0700
parents c123ee15f99b
children 49fb4e83484f
line wrap: on
line source

package luan.webserver.handlers;

import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import luan.webserver.Handler;
import luan.webserver.Request;
import luan.webserver.Response;
import luan.webserver.ResponseOutputStream;
import luan.webserver.Status;


public final class SafeHandler implements Handler {
	private static final Logger logger = LoggerFactory.getLogger(SafeHandler.class);

	private final Handler handler;

	public SafeHandler(Handler handler) {
		this.handler = handler;
	}

	public Response handle(Request request) {
		try {
			Response response = handler.handle(request);
			if( response != null )
				return response;
		} catch(RuntimeException e) {
			logger.error("",e);
			Response response = new Response();
			response.status = Status.INTERNAL_SERVER_ERROR;
			response.headers.put( "Content-Type", "text/plain; charset=UTF-8" );
			PrintWriter writer = new PrintWriter( new ResponseOutputStream(response) );
			writer.write( "Internel Server Error\n\n" );
			e.printStackTrace(writer);
			writer.close();
			return response;
		}

		Response response = new Response();
		response.status = Status.NOT_FOUND;
		response.headers.put( "Content-Type", "text/plain; charset=UTF-8" );
		try {
			Writer writer = new OutputStreamWriter( new ResponseOutputStream(response) );
			writer.write( request.path+" not found\n" );
			writer.close();
		} catch(IOException e) {
			throw new RuntimeException(e);
		}
		return response;
	}

}