To implement exception handling and custom error messages in an Akka HTTP application, follow these steps:
1. Define custom exception classes extending RuntimeException or another suitable base class.
2. Create a trait with a ExceptionHandler method that pattern matches on exceptions thrown within routes and maps them to appropriate HTTP responses containing meaningful information for clients.
3. Mix the trait into your main server object or route definition.
4. Use handleExceptions directive in your route definition to apply the custom exception handler.
class CustomException(msg: String) extends RuntimeException(msg)
trait CustomExceptionHandler {
implicit def myExceptionHandler: ExceptionHandler =
ExceptionHandler {
case e: CustomException =>
extractUri { uri =>
log.error(s"Request to $uri failed with ${e.getMessage}")
complete(HttpResponse(StatusCodes.BadRequest, entity = e.getMessage))
}
}
}
object MyServer extends App with CustomExceptionHandler {
val route = handleExceptions(myExceptionHandler) {
path("example") {
throw new CustomException("Custom error message")
}
}
Http().bindAndHandle(route, "localhost", 8080)
}?