pyc-website
main website for pyc inc.
git clone https://9o.is/git/pyc-website.git
ErrorHandler.scala
(1879B)
1 package inc.pyc
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]("/error") {} // where to send the user when an error occurs
14
15 def init(): Unit = {
16 LiftRules.exceptionHandler.prepend {
17 case (Props.RunModes.Development, r, e) =>
18 logException(r, e)
19 XhtmlResponse(
20 (<html><body>Exception occured while processing {r.uri}<pre>{showException(e)}</pre></body></html>),
21 S.htmlProperties.docType,
22 List("Content-Type" -> "text/html; charset=utf-8"),
23 Nil,
24 500,
25 S.legacyIeCompatibilityMode
26 )
27 case (_, r, e) =>
28 logException(r, e)
29 RedirectResponse(errorUrl.vend)
30 }
31 }
32
33 /*
34 * Log the exception with some user info.
35 */
36 def logException(r: Req, e: Throwable) {
37 import java.net.InetAddress
38 val srvr = InetAddress.getLocalHost.getHostName
39
40 MDC.put(("UserId", User.currentUserId openOr "GUEST"))
41 MDC.put(("Username", User.currentUser.map(_.username.get) openOr "GUEST"))
42 MDC.put(("User Agent", r.userAgent openOr "UNKNOWN"))
43 MDC.put(("Server", srvr))
44 logger.error("Exception occurred while processing %s".format(r.uri), e)
45 }
46
47 /**
48 * A utility method to convert an exception to a string of stack traces
49 * @param le the exception
50 *
51 * @return the stack trace
52 */
53 def showException(le: Throwable): String = {
54 val ret = "Message: " + le.toString + "\n\t" +
55 le.getStackTrace.map(_.toString).mkString("\n\t") + "\n"
56
57 val also = le.getCause match {
58 case null => ""
59 case sub: Throwable => "\nCaught and thrown by:\n" + showException(sub)
60 }
61
62 ret + also
63 }
64 }