scala-news-reader
rss/atom news reader in scala
git clone https://9o.is/git/scala-news-reader.git
ErrorHandler.scala
(1899B)
1 package com.joereader
2 package config
3
4 import model.User
5
6 import net.liftweb._
7 import common.{Loggable, MDC}
8 import http.{Factory, LiftRules, RedirectResponse, Req, S, XhtmlResponse}
9 import util.Props
10
11 object ErrorHandler extends Factory with Loggable {
12 // config
13 val errorUrl = new FactoryMaker[String](Site.error.url) {}
14
15 def init(): Unit = {
16 LiftRules.exceptionHandler.prepend {
17 case (Props.RunModes.Development, r, e) =>
18 logException(r, e)
19 XhtmlResponse(
20 <html>
21 <body>Exception occured while processing
22 {r.uri}<pre>
23 {showException(e)}
24 </pre>
25 </body>
26 </html>,
27 S.htmlProperties.docType,
28 List("Content-Type" -> "text/html; charset=utf-8"),
29 Nil,
30 500,
31 S.ieMode
32 )
33 case (_, r, e) =>
34 logException(r, e)
35 RedirectResponse(errorUrl.vend)
36 }
37 }
38
39 /*
40 * Log the exception with some user info.
41 */
42 def logException(r: Req, e: Throwable) {
43 import java.net.InetAddress
44 val srvr = InetAddress.getLocalHost.getHostName
45
46 MDC.put(("UserId", User.currentUserId openOr "GUEST"))
47 MDC.put(("Username", User.currentUser.map(_.username.is) openOr "GUEST"))
48 MDC.put(("User Agent", r.userAgent openOr "UNKNOWN"))
49 MDC.put(("Server", srvr))
50 logger.error("Exception occurred while processing %s".format(r.uri), e)
51 }
52
53 /**
54 * A utility method to convert an exception to a string of stack traces
55 * @param le the exception
56 *
57 * @return the stack trace
58 */
59 def showException(le: Throwable): String = {
60 val ret = "Message: " + le.toString + "\n\t" +
61 le.getStackTrace.map(_.toString).mkString("\n\t") + "\n"
62
63 val also = le.getCause match {
64 case null => ""
65 case sub: Throwable => "\nCaught and thrown by:\n" + showException(sub)
66 }
67
68 ret + also
69 }
70 }