Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling in play framework

I am developing a REST API using play framework. I would like to implement a centralized error handling for all my actions.

What is the best way to achieve this?

like image 897
jfu Avatar asked Aug 28 '14 11:08

jfu


People also ask

What is error handling framework?

The error handling framework should also classify the errors that can be re-processed so that the process doesn't restart from the source. Provided above is an overview of the process and its benefits. • For low error rate, handle each error individually. • Open connection to storage, save error packages for.

What is error handling in vb6?

The Visual Basic error handling model allows programmers to perform special actions when an error occurs, such as jumping to a particular line of code.

What is good error handling?

A good error handler will log errors so they can be reviewed and analyzed. It will also provide the operator with a recall function to open the error log file and display errors. In addition, a good error handler logs all the errors, not just the ones that caused the error resolving to occur.


2 Answers

An alternative way do this is to use a filter, e.g:

object ExceptionFilter extends EssentialFilter {
  def apply(nextFilter: EssentialAction) = new EssentialAction {
    def apply(requestHeader: RequestHeader) = {
      val next: Iteratee[Array[Byte], Result] = nextFilter(requestHeader)

      // Say your backend throws an ItemNotFound exception.
      next recoverWith {
        case e: ItemNotFound => Iteratee.ignore[Array[Byte]]
          .map(_ => Results.NotFound("Item not in the database!"))
      }
    }
  }
}

Then hook that up in your global settings:

object Global extends WithFilters(CSRFFilter(), ExceptionFilter) with GlobalSettings

This potentially allows you to do something with the request body if needed. I agree in most cases using GlobalSettings.onError is probably the easiest approach.

like image 179
Mikesname Avatar answered Sep 21 '22 08:09

Mikesname


You should have a look at the GlobalSettings: https://www.playframework.com/documentation/2.3.x/ScalaGlobal

Especially, it allows you to override:

def onError(request: RequestHeader, ex: Throwable)
def onHandlerNotFound(request: RequestHeader)
def onBadRequest(request: RequestHeader, error: String)

onError is probably the one you are looking for, but the others may be useful too :)

like image 21
vptheron Avatar answered Sep 21 '22 08:09

vptheron