是否可以使用dropwizard设置404的全局品牌错误页面

时间:2013-01-24 11:35:48

标签: grails embedded-jetty dropwizard

我发现自己正在使用grails应用程序,该应用程序被部署为由自定义插件构建的胖jar,该插件使用dropwizard配置jetty。

似乎dropwizard不允许使用普通的旧web.xml或jetty.xml,而是在启动时由java config设置所有内容(即使用com.yammer.dropwizard.config.Environment)。

我在这里遗漏了什么吗?有没有办法将404映射回URL或我可以覆盖的任何类型的网页,以便Jetty 404不是默认值。

(是的,我知道我可以使用负载均衡器重定向404s)

1 个答案:

答案 0 :(得分:0)

我不知道它是如何在grails中,但这有助于java与dropwizard 0.7.1 run()方法:

ResourceConfig jrConfig = environment.jersey().getResourceConfig();
environment.jersey().register(new RestErrorsHandler(jrConfig ));

为异常映射创建此类 - >回馈个人回复!

@Provider
public class RestErrorsHandler implements ExceptionMapper<Exception> {

/**
 * Deletes all ExpetionMappers.
 * 
 * @param jrConfig
 */
public RestErrorsHandler(
    ResourceConfig jrConfig)
{
    // Remove all of Dropwizard's custom ExceptionMappers
    Set<?> dwSingletons = jrConfig.getSingletons();
    List<Object> singletonsToRemove = new ArrayList<Object>();
    for (Object s : dwSingletons) {
            // Remove all Exception mappers
            if (s instanceof ExceptionMapper) {
                singletonsToRemove.add(s);
            }
    }
    for (Object s : singletonsToRemove) {
        jrConfig.getSingletons().remove(s);
    }
}

public Response toResponse(
    Exception exception)
{   
    //Handle different exceptions in another way
    if (exception.getClass().equals(JsonParseException.class)){
        Response response = RestErrorsHandler.generalResponse(exception);
        return response ;
    } else if(exception.getClass().equals(JsonParseException.class)){
        Response response = RestErrorsHandler.generalResponse(exception);
        return response ;
    } else if(exception.getClass().equals(Class.class)){
        Response response = RestErrorsHandler.generalResponse(exception);
        return response ;
    }

    //genral problem -> output default
    Response response = RestErrorsHandler.generalResponse(exception);
    return response ;

}

public static Response generalResponse(Exception exception)
{
    return Response.status(Status.BAD_REQUEST).type(MediaType.TEXT_PLAIN)
        .entity("if you just want to give back a string, but could also be default html page or whatever").build();
}



}