Overrode Play’s ErrorHandler class (see ManagementAppErrorPlayHandler and application.conf) so that we any exception thrown, we response with a meaningful JSON
Used Scala’s Stackable Trace pattern so that ManagementAppErrorPlayHandler can find the proper handler for a thrown exception
Used PartialFunction to define the type of error resolver. With PartialFunction we can easily compose/combine handlers. An error resolver (or handler) is a just a partial function that when turn a thrown exception to the proper play Result that should be sent as http response.
Created a new DTO called ErrorMessageDTO. This is for server to send a formatted JSON message to front-end, and then our web app can display meaningful error message according to the JSON sent
A custom exception or error message has these fields: exceptionCode(an unique exception code), status (http status code), code (exception title), message (detailed exception message)
Implemented an error message formatter so that we can see meaningful message on terminal
Here’s how error-handling works:
For a specific use case, define an custom exception to extend AbstractManagementAppException, and then when throwing the exception, define a unique MAExceptionCode (when looking at stack trace, we can easily find exactly where the exception was thrown using the exception code)
After an exception is thrown, the ManagementAppErrorPlayHandler will catch the exception, and then through the stack of handler traits (BaseErrorHandler, CommonErrorHandler, AuthenticationErrorHandler, etc), it will find the a appropriate handler for the error
The handler will turn the error to a proper play Result (see handler traits and MAErrorResults), and then send the Result response back to client
(Inspired by: http://stackoverflow.com/questions/30351481/play-framework-how-to-implement-proper-error-handling) (Stackable Trait Pattern: http://www.artima.com/scalazine/articles/stackable_trait_pattern.html) (Scala PartialFunctions: http://alvinalexander.com/scala/how-to-define-use-partial-functions-in-scala-syntax-examples)
Implementations:
Here’s how error-handling works: