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?
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.
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.
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.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With