Advertisement
Guest User

ExceptionHandling

a guest
Jul 28th, 2015
243
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.88 KB | None | 0 0
  1. import scala.util.{Failure, Success, Try}
  2.  
  3. trait Logging {
  4.   def log(message: String): Unit = println(s"[LOG]: $message")
  5. }
  6.  
  7. trait ExceptionLogger {
  8.   def logExceptions[T]: PartialFunction[Throwable, Try[T]]
  9. }
  10.  
  11. trait ExceptionMapper {
  12.   def mapExceptions[T]: PartialFunction[Throwable, Try[T]]
  13. }
  14.  
  15. trait ExceptionHandler {
  16.   def exceptionHandler[T]: PartialFunction[Throwable, Try[T]]
  17. }
  18.  
  19. object ExceptionHandling {
  20.   def defaultExceptionHandler[T]: PartialFunction[Throwable, Try[T]] = {
  21.     case e: Exception =>
  22.       println("DefaultHandler")
  23.       Failure(e)
  24.   }
  25. }
  26.  
  27. trait ExceptionHandling extends ExceptionHandler with ExceptionMapper with ExceptionLogger {
  28.   import ExceptionHandling._
  29.   def handleExceptions[T](code: => T): T = {
  30.     Try(code) recoverWith {
  31.       exceptionHandler orElse defaultExceptionHandler
  32.     } recoverWith logExceptions recoverWith mapExceptions get
  33.   }
  34. }
  35.  
  36. trait DefaultExceptionHandler extends ExceptionHandler {
  37.   override def exceptionHandler[T]: PartialFunction[Throwable, Try[T]] = PartialFunction.empty
  38. }
  39.  
  40. trait DefaultExceptionsLogger extends ExceptionLogger {
  41.   this: Logging =>
  42.   override def logExceptions[T]: PartialFunction[Throwable, Try[T]] = {
  43.     case e: Throwable =>
  44.       log(e.getMessage)
  45.       Failure(e)
  46.   }
  47. }
  48.  
  49.  
  50. // Generated
  51. class WebServiceException(message: String) extends Exception(message)
  52.  
  53. class WebService {
  54.   this: ExceptionHandling =>
  55.   def method(): String = handleExceptions {
  56.     throw new Exception("An exception")
  57.   }
  58.  
  59.   override def mapExceptions[T]: PartialFunction[Throwable, Try[T]] = {
  60.     case e: Exception => Failure(new WebServiceException(e.getMessage))
  61.   }
  62. }
  63.  
  64.  
  65. try {
  66.   val service = new WebService with ExceptionHandling with DefaultExceptionHandler
  67.     with DefaultExceptionsLogger with Logging
  68.   service.method()
  69. } catch {
  70.   case e: WebServiceException => println("Success!")
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement