question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Global onError doesn't called for FakeApplication (tests)

See original GitHub issue

Reproduced on Play 2.2.2

  1. Catch all errors and handle them in Global.scala

    import play.api._
    import play.api.mvc.{Results, WithFilters}
    import scala.concurrent.Future
    
    object Global extends GlobalSettings {
        override def onError(request : play.api.mvc.RequestHeader, ex : Throwable) : scala.concurrent.Future[play.api.mvc.SimpleResult] = {
                Future.successful(Results.BadRequest)
        }
    }
    
  2. Generate exception in action

    package controllers
    
    import play.api._
    import play.api.mvc._
    
    object Application extends Controller {
      def index = Action {
        throw new RuntimeException("Unexpected")
        Ok
      }
    }
    
  3. The problem is that if you call that action in browser, you’ll get 400 BAD_REQUEST exactly like it’s handled in Global.scala, but you can’t cover it with test because this test fails with exception:

    @RunWith(classOf[JUnitRunner]) class ApplicationSpec extends Specification { “Application” should { “render the index page” in new WithApplication{ val home = route(FakeRequest(GET, “/”)).get status(home) must equalTo(BAD_REQUEST) } } }

Issue Analytics

  • State:closed
  • Created 10 years ago
  • Comments:10 (5 by maintainers)

github_iconTop GitHub Comments

11reactions
scadgekcommented, Sep 20, 2017

Hi @jroper,

Just wanted to inquire whether you haven’t changed your position after 3 years. I can find a few counterarguments to your claim that we don’t need to test onError()'s behaviour when testing controllers. In my view, when I test a controller, what I want to accomplish is to emulate someone issuing an HTTP request to my service and test the result he receives, which is in this case the result on onError()'s execution. At the same time, if I want to test that the proper exception is thrown, I’ll test the underlying controller’s class, and this will also encourage decoupling of business logic from the router’s logic.

Of course, the approach you suggested - writing tests for the HttpErrorHandler itself - would also work, but I believe this makes testing the controller either redundant or incomplete, since it does nothing besides parsing request and by itself does not throw any exceptions - instead it returns Result instances.

Please tell us what you think of this, and thanks in advance!

3reactions
zarinfamcommented, Jul 10, 2016

Java 8 version of routeWithOnError for play 2.4+:

public static Result routeWithOnError(Http.RequestBuilder requestBuilder) throws InterruptedException, ExecutionException, TimeoutException {
    CompletableFuture<Result> future = CompletableFuture.supplyAsync(() -> route(requestBuilder));

    BiFunction<Result, Throwable, CompletionStage<Result>> f =
            (r, t) -> (t == null)
                    ? CompletableFuture.supplyAsync(() -> r)
                    : new CustomHttpErrorHandler().onError(null, t);

    return future.handleAsync(f).thenCompose(x -> x).get(20000, TimeUnit.MILLISECONDS);
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

Handling operation errors - Apollo GraphQL Docs
Apollo Client can encounter a variety of errors when executing operations on your GraphQL server. Apollo Client helps you handle these errors according...
Read more >
Unit testing window.onerror with jasmine - Stack Overflow
I recently developed small JavaScript error handler with unit tests based on Buster.JS which is similar to Jasmine.
Read more >
How to Handle Application_error in ASP.NET App's Global.asax
One common error is an Application_error in the Global.asax file. How to handle ASP.NET App's Global.asax and other common errors in .NET.
Read more >
Window: error event - Web APIs - MDN Web Docs - Mozilla
Use the event name in methods like addEventListener() , or set an event handler property. addEventListener("error", (event) => {}); onerror ...
Read more >
How to create a Global Error Handler in Mule 4 to unify your ...
This Global Error Handling strategy is used by any Mule application flow that does not have its own error handling strategy. We can...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found