Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.util.{Failure, Success, Try}
- trait Logging {
- def log(message: String): Unit = println(s"[LOG]: $message")
- }
- trait ExceptionLogger {
- def logExceptions[T]: PartialFunction[Throwable, Try[T]]
- }
- trait ExceptionMapper {
- def mapExceptions[T]: PartialFunction[Throwable, Try[T]]
- }
- trait ExceptionHandler {
- def exceptionHandler[T]: PartialFunction[Throwable, Try[T]]
- }
- object ExceptionHandling {
- def defaultExceptionHandler[T]: PartialFunction[Throwable, Try[T]] = {
- case e: Exception =>
- println("DefaultHandler")
- Failure(e)
- }
- }
- trait ExceptionHandling extends ExceptionHandler with ExceptionMapper with ExceptionLogger {
- import ExceptionHandling._
- def handleExceptions[T](code: => T): T = {
- Try(code) recoverWith {
- exceptionHandler orElse defaultExceptionHandler
- } recoverWith logExceptions recoverWith mapExceptions get
- }
- }
- trait DefaultExceptionHandler extends ExceptionHandler {
- override def exceptionHandler[T]: PartialFunction[Throwable, Try[T]] = PartialFunction.empty
- }
- trait DefaultExceptionsLogger extends ExceptionLogger {
- this: Logging =>
- override def logExceptions[T]: PartialFunction[Throwable, Try[T]] = {
- case e: Throwable =>
- log(e.getMessage)
- Failure(e)
- }
- }
- // Generated
- class WebServiceException(message: String) extends Exception(message)
- class WebService {
- this: ExceptionHandling =>
- def method(): String = handleExceptions {
- throw new Exception("An exception")
- }
- override def mapExceptions[T]: PartialFunction[Throwable, Try[T]] = {
- case e: Exception => Failure(new WebServiceException(e.getMessage))
- }
- }
- try {
- val service = new WebService with ExceptionHandling with DefaultExceptionHandler
- with DefaultExceptionsLogger with Logging
- service.method()
- } catch {
- case e: WebServiceException => println("Success!")
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement