简体   繁体   中英

Global Exception Handling in play framework java 2.3.7

I am trying to implement global exception handling in Play framework(RESTful) using Java. While searching I found out that extending GlobalSettings and overriding the onError method should handle all errors and give the appropriate response/view. But in the console where I execute "activator run", I still get the ugly stack trace of the exception. Is there a way to stop printing the stack trace or is Play framework really handling the exception?

    @Override
    public Promise<Result> onError(RequestHeader request, Throwable t) {
       return Promise.<Result>pure(Results.status(200, tr.getLocalizedMessage()));
    }

I had the same issue. Somehow the logging happens independent of the onError() method in Global. I solved this with Action composition .

public class VerboseAction extends play.mvc.Action.Simple {

    public F.Promise<Result> call(Http.Context ctx) throws Throwable {
        Promise<Result> call;
        try {
            call = delegate.call(ctx);
        } catch (Exception e) {
            Logger.error("Exception during call " + Controller.request().uri()
                    + ": " + e.getMessage(), e);
            call = Promise.<Result> pure(redirect(controllers.routes.Home
                    .error(e.getMessage())));
        }
        return call;
    }
}

Just annotate your Controller or your Controller methods with this new annotations and all exceptions will be caught. You could catch different exceptions and handle them differently. Also, if you have Ajax calls you don't want to return / redirect to a website.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM