{-|
Module: IHP.ErrorController
Description:  Provides web-based error screens for runtime errors in IHP
Copyright: (c) digitally induced GmbH, 2020
-}
module IHP.ErrorController
( displayException
, handleNoResponseReturned
, handleNotFound
, handleRouterException
) where

import IHP.Prelude hiding (displayException)
import qualified IHP.Controller.Param as Param
import qualified IHP.Router.Types as Router
import qualified Control.Exception as Exception
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import System.IO (stderr)
import IHP.Controller.RequestContext
import Network.HTTP.Types (status500, status404, status400)
import Network.Wai
import Network.HTTP.Types.Header

import Text.Blaze.Html5 ((!))
import qualified Text.Blaze.Html5            as H
import qualified Text.Blaze.Html5.Attributes as A
import qualified Text.Blaze.Html.Renderer.Utf8 as Blaze
import qualified Database.PostgreSQL.Simple as PG
import qualified Database.PostgreSQL.Simple.FromField as PG
import qualified Data.ByteString.Char8 as ByteString

import IHP.HtmlSupport.QQ (hsx)
import Database.PostgreSQL.Simple.FromField (ResultError (..))
import qualified IHP.ModelSupport as ModelSupport
import IHP.FrameworkConfig
import qualified IHP.Environment as Environment
import IHP.Controller.Context
import qualified System.Directory as Directory
import qualified IHP.Log as Log

handleNoResponseReturned :: (Show controller, ?context :: ControllerContext) => controller -> IO ResponseReceived
handleNoResponseReturned :: controller -> IO ResponseReceived
handleNoResponseReturned controller
controller = do
    let Text
codeSample :: Text = Text
"render MyView { .. }"
    let errorMessage :: Html
errorMessage = [hsx|
            <h2>Possible Solutions</h2>
            <p>You can fix this by calling '{codeSample}' at the end of your action.</p>

            <h2>Details</h2>
            <p style="font-size: 16px">No response was returned while running the action {tshow controller}</p>

        |]
    let title :: Html
title = [hsx|No response returned in {tshow controller}|]
    let RequestContext { Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = Proxy "requestContext" -> ControllerContext -> RequestContext
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "requestContext" (Proxy "requestContext")
Proxy "requestContext"
#requestContext ?context::ControllerContext
ControllerContext
?context
    Respond
respond Respond -> Respond
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status500 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
title Html
errorMessage))

-- | Renders a 404 not found response. If a static/404.html exists, that is rendered instead of the IHP not found page
handleNotFound :: (?context :: RequestContext) => IO ResponseReceived
handleNotFound :: IO ResponseReceived
handleNotFound = do
    Bool
hasCustomNotFound <- String -> IO Bool
Directory.doesFileExist String
"static/404.html"
    let response :: Response
response = if Bool
hasCustomNotFound
            then Response
customNotFoundResponse
            else Response
(?context::RequestContext) => Response
defaultNotFoundResponse

    let RequestContext { Respond
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = ?context::RequestContext
RequestContext
?context
    Respond
respond Response
response

-- | The default IHP 404 not found page
defaultNotFoundResponse :: (?context :: RequestContext) => Response
defaultNotFoundResponse :: Response
defaultNotFoundResponse = do
    let errorMessage :: Html
errorMessage = [hsx|Router failed to find an action to handle this request.|]
    let title :: Html
title = Text -> Html
H.text Text
"Action Not Found"
    Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status404 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
title Html
errorMessage))

-- | Renders the static/404.html file
customNotFoundResponse :: Response
customNotFoundResponse :: Response
customNotFoundResponse = Status -> ResponseHeaders -> String -> Maybe FilePart -> Response
responseFile Status
status404 [(HeaderName
hContentType, ByteString
"text/html")] String
"static/404.html" Maybe FilePart
forall a. Maybe a
Nothing

displayException :: (Show action, ?context :: ControllerContext) => SomeException -> action -> Text -> IO ResponseReceived
displayException :: SomeException -> action -> Text -> IO ResponseReceived
displayException SomeException
exception action
action Text
additionalInfo = do
    -- Dev handlers display helpful tips on how to resolve the problem
    let devHandlers :: [SomeException -> action -> Text -> Maybe (IO ResponseReceived)]
devHandlers =
            [ SomeException -> action -> Text -> Maybe (IO ResponseReceived)
forall controller.
(Show controller, ?context::ControllerContext) =>
SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
postgresHandler
            , SomeException -> action -> Text -> Maybe (IO ResponseReceived)
forall controller.
(Show controller, ?context::ControllerContext) =>
SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
paramNotFoundExceptionHandler
            , SomeException -> action -> Text -> Maybe (IO ResponseReceived)
forall controller.
(Show controller, ?context::ControllerContext) =>
SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
patternMatchFailureHandler
            , SomeException -> action -> Text -> Maybe (IO ResponseReceived)
forall controller.
(Show controller, ?context::ControllerContext) =>
SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
recordNotFoundExceptionHandlerDev
            , SomeException -> action -> Text -> Maybe (IO ResponseReceived)
forall controller.
(?context::ControllerContext) =>
SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
handleInvalidActionArgumentExceptionDev
            ]

    -- Prod handlers should not leak any information about the system
    let prodHandlers :: [SomeException -> action -> Text -> Maybe (IO ResponseReceived)]
prodHandlers =
            [ SomeException -> action -> Text -> Maybe (IO ResponseReceived)
forall controller.
(Show controller, ?context::ControllerContext) =>
SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
recordNotFoundExceptionHandlerProd
            , SomeException -> action -> Text -> Maybe (IO ResponseReceived)
forall controller.
(?context::ControllerContext) =>
SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
handleInvalidActionArgumentExceptionProd
            ]

    let allHandlers :: [SomeException -> action -> Text -> Maybe (IO ResponseReceived)]
allHandlers = if (FrameworkConfig -> Environment) -> Environment
forall context a.
(?context::context, ConfigProvider context) =>
(FrameworkConfig -> a) -> a
fromConfig FrameworkConfig -> Environment
environment Environment -> Environment -> Bool
forall a. Eq a => a -> a -> Bool
== Environment
Environment.Development
            then [SomeException -> action -> Text -> Maybe (IO ResponseReceived)]
devHandlers
            else [SomeException -> action -> Text -> Maybe (IO ResponseReceived)]
prodHandlers

    let supportingHandlers :: [IO ResponseReceived]
supportingHandlers = [SomeException -> action -> Text -> Maybe (IO ResponseReceived)]
allHandlers [SomeException -> action -> Text -> Maybe (IO ResponseReceived)]
-> ([SomeException
     -> action -> Text -> Maybe (IO ResponseReceived)]
    -> [IO ResponseReceived])
-> [IO ResponseReceived]
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> ((SomeException -> action -> Text -> Maybe (IO ResponseReceived))
 -> Maybe (IO ResponseReceived))
-> [SomeException -> action -> Text -> Maybe (IO ResponseReceived)]
-> [IO ResponseReceived]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe (\SomeException -> action -> Text -> Maybe (IO ResponseReceived)
f -> SomeException -> action -> Text -> Maybe (IO ResponseReceived)
f SomeException
exception action
action Text
additionalInfo)

    -- Additionally to rendering the error message to the browser we also log
    -- the error message because sometimes you cannot easily access the http response
    Text -> IO ()
forall context.
(?context::context, LoggingProvider context) =>
Text -> IO ()
Log.error (Text -> IO ()) -> Text -> IO ()
forall a b. (a -> b) -> a -> b
$ SomeException -> Text
forall a. Show a => a -> Text
tshow SomeException
exception

    let displayGenericError :: IO ResponseReceived
displayGenericError = SomeException -> action -> Text -> IO ResponseReceived
forall controller.
(Show controller, ?context::ControllerContext) =>
SomeException -> controller -> Text -> IO ResponseReceived
genericHandler SomeException
exception action
action Text
additionalInfo

    [IO ResponseReceived]
supportingHandlers
        [IO ResponseReceived]
-> ([IO ResponseReceived] -> Maybe (IO ResponseReceived))
-> Maybe (IO ResponseReceived)
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> [IO ResponseReceived] -> Maybe (IO ResponseReceived)
forall a. [a] -> Maybe a
head
        Maybe (IO ResponseReceived)
-> (Maybe (IO ResponseReceived) -> IO ResponseReceived)
-> IO ResponseReceived
forall t1 t2. t1 -> (t1 -> t2) -> t2
|> IO ResponseReceived
-> Maybe (IO ResponseReceived) -> IO ResponseReceived
forall a. a -> Maybe a -> a
fromMaybe IO ResponseReceived
displayGenericError

-- | Responds to all exceptions with a generic error message.
--
-- In dev mode the action and exception is added to the output.
-- In production mode nothing is specific is communicated about the exception
genericHandler :: (Show controller, ?context :: ControllerContext) => Exception.SomeException -> controller -> Text -> IO ResponseReceived
genericHandler :: SomeException -> controller -> Text -> IO ResponseReceived
genericHandler SomeException
exception controller
controller Text
additionalInfo = do
    let devErrorMessage :: Html
devErrorMessage = [hsx|An exception was raised while running the action {tshow controller}{additionalInfo}|]
    let devTitle :: Html
devTitle = [hsx|{Exception.displayException exception}|]

    let prodErrorMessage :: Html
prodErrorMessage = [hsx|An exception was raised while running the action|]
    let prodTitle :: Html
prodTitle = [hsx|An error happend|]

    let (Html
errorMessage, Html
errorTitle) = if (FrameworkConfig -> Environment) -> Environment
forall context a.
(?context::context, ConfigProvider context) =>
(FrameworkConfig -> a) -> a
fromConfig FrameworkConfig -> Environment
environment Environment -> Environment -> Bool
forall a. Eq a => a -> a -> Bool
== Environment
Environment.Development
            then (Html
devErrorMessage, Html
devTitle)
            else (Html
prodErrorMessage, Html
prodTitle)
    let RequestContext { Respond
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = Proxy "requestContext" -> ControllerContext -> RequestContext
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "requestContext" (Proxy "requestContext")
Proxy "requestContext"
#requestContext ?context::ControllerContext
ControllerContext
?context

    Respond
respond Respond -> Respond
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status500 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
errorTitle Html
errorMessage))

postgresHandler :: (Show controller, ?context :: ControllerContext) => SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
postgresHandler :: SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
postgresHandler SomeException
exception controller
controller Text
additionalInfo = do
    let
        handlePostgresError :: Show exception => exception -> Text -> IO ResponseReceived
        handlePostgresError :: exception -> Text -> IO ResponseReceived
handlePostgresError exception
exception Text
errorText =
            let
                title :: Html
title = Text -> Html
H.text (Text
"Database looks outdated. " Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
errorText)
                errorMessage :: Html
errorMessage = [hsx|
                        <h2>Possible Solutions</h2>
                        <div style="margin-bottom: 2rem; font-weight: 400;">
                            Have you clicked on
                            <form method="POST" action="http://localhost:8001/UpdateDb" target="_blank" style="display: inline">
                                <button type="submit">Update DB</button>
                            </form>
                            after updating the Schema?
                        </div>

                        <h2>Details</h2>
                        <p style="font-size: 16px">The exception was raised while running the action: {tshow controller}{additionalInfo}</p>
                        <p style="font-family: monospace; font-size: 16px">{tshow exception}</p>
                    |]
            in do
                let RequestContext { Respond
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = Proxy "requestContext" -> ControllerContext -> RequestContext
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "requestContext" (Proxy "requestContext")
Proxy "requestContext"
#requestContext ?context::ControllerContext
ControllerContext
?context
                Respond
respond Respond -> Respond
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status500 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
title Html
errorMessage))
    case SomeException -> Maybe ResultError
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
        Just (ResultError
exception :: PG.ResultError) -> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just (ResultError -> Text -> IO ResponseReceived
forall exception.
Show exception =>
exception -> Text -> IO ResponseReceived
handlePostgresError ResultError
exception Text
"The database result does not match the expected type.")
        Maybe ResultError
Nothing -> case SomeException -> Maybe SqlError
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
            -- Catching  `relation "..." does not exist`
            Just (SqlError
exception :: PG.SqlError)
                |  ByteString
"relation" ByteString -> ByteString -> Bool
`ByteString.isPrefixOf` (Proxy "sqlErrorMsg" -> SqlError -> ByteString
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "sqlErrorMsg" (Proxy "sqlErrorMsg")
Proxy "sqlErrorMsg"
#sqlErrorMsg SqlError
exception)
                Bool -> Bool -> Bool
&& ByteString
"does not exist" ByteString -> ByteString -> Bool
`ByteString.isSuffixOf` (Proxy "sqlErrorMsg" -> SqlError -> ByteString
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "sqlErrorMsg" (Proxy "sqlErrorMsg")
Proxy "sqlErrorMsg"
#sqlErrorMsg SqlError
exception)
                -> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just (SqlError -> Text -> IO ResponseReceived
forall exception.
Show exception =>
exception -> Text -> IO ResponseReceived
handlePostgresError SqlError
exception Text
"A table is missing.")
            Maybe SqlError
_ -> Maybe (IO ResponseReceived)
forall a. Maybe a
Nothing

patternMatchFailureHandler :: (Show controller, ?context :: ControllerContext) => SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
patternMatchFailureHandler :: SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
patternMatchFailureHandler SomeException
exception controller
controller Text
additionalInfo = do
    case SomeException -> Maybe PatternMatchFail
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
        Just (PatternMatchFail
exception :: Exception.PatternMatchFail) -> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just do
            let (Text
controllerPath, Text
_) = Text -> Text -> (Text, Text)
Text.breakOn Text
":" (PatternMatchFail -> Text
forall a. Show a => a -> Text
tshow PatternMatchFail
exception)
            let errorMessage :: Html
errorMessage = [hsx|
                    <h2>Possible Solutions</h2>
                    <p>a) Maybe the action function is missing for {tshow controller}? You can fix this by adding an action handler like this to the controller '{controllerPath}':</p>
                    <pre>{codeSample}</pre>
                    <p style="margin-bottom: 2rem">b) A pattern match like 'let (Just value) = ...' failed. Please see the details section.</p>

                    <h2>Details</h2>
                    <p style="font-size: 16px">{exception}</p>
                |]
                    where
                        codeSample :: Text
codeSample = Text
"    action (" Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> controller -> Text
forall a. Show a => a -> Text
tshow controller
controller Text -> Text -> Text
forall a. Semigroup a => a -> a -> a
<> Text
") = do\n        renderPlain \"Hello World\""

            let title :: Html
title = [hsx|Pattern match failed while executing {tshow controller}|]
            let RequestContext { Respond
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = Proxy "requestContext" -> ControllerContext -> RequestContext
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "requestContext" (Proxy "requestContext")
Proxy "requestContext"
#requestContext ?context::ControllerContext
ControllerContext
?context
            Respond
respond Respond -> Respond
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status500 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
title Html
errorMessage))
        Maybe PatternMatchFail
Nothing -> Maybe (IO ResponseReceived)
forall a. Maybe a
Nothing

-- Handler for 'IHP.Controller.Param.ParamNotFoundException'
paramNotFoundExceptionHandler :: (Show controller, ?context :: ControllerContext) => SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
paramNotFoundExceptionHandler :: SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
paramNotFoundExceptionHandler SomeException
exception controller
controller Text
additionalInfo = do
    case SomeException -> Maybe ParamException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
        Just (exception :: ParamException
exception@(Param.ParamNotFoundException ByteString
paramName)) -> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just do
            let (Text
controllerPath, Text
_) = Text -> Text -> (Text, Text)
Text.breakOn Text
":" (ParamException -> Text
forall a. Show a => a -> Text
tshow ParamException
exception)

            let renderParam :: (a, a) -> Html
renderParam (a
paramName, a
paramValue) = [hsx|<li>{paramName}: {paramValue}</li>|]
            let solutionHint :: Html
solutionHint =
                    if [(ByteString, Maybe ByteString)] -> Bool
forall value. IsEmpty value => value -> Bool
isEmpty [(ByteString, Maybe ByteString)]
(?context::ControllerContext) => [(ByteString, Maybe ByteString)]
Param.allParams
                        then [hsx|
                                This action was called without any parameters at all.
                                You can pass this parameter by appending <code>?{paramName}=someValue</code> to the URL.
                            |]
                        else [hsx|
                            <p>The following parameters are provided by the request:</p>
                            <ul>{forEach Param.allParams renderParam}</ul>

                            <p>a) Is there a typo in your call to <code>param {tshow paramName}</code>?</p>
                            <p>b) You can pass this parameter by appending <code>&{paramName}=someValue</code> to the URL.</p>
                            <p>c) You can pass this parameter using a form input like <code>{"<input type=\"text\" name=\"" <> paramName <> "\"/>" :: ByteString}</code>.</p>
                        |]
            let errorMessage :: Html
errorMessage = [hsx|
                    <h2>
                        This exception was caused by a call to <code>param {tshow paramName}</code> in {tshow controller}.
                    </h2>
                    <p>
                        A request parameter is just a query parameter like <code>/MyAction?someParameter=someValue&secondParameter=1</code>
                        or a form input when the request was submitted from a html form or via ajax.
                    </p>
                    <h2>Possible Solutions:</h2>
                    {solutionHint}

                    <h2>Details</h2>
                    <p style="font-size: 16px">{exception}</p>
                |]



            let title :: Html
title = [hsx|Parameter <q>{paramName}</q> not found in the request|]
            let RequestContext { Respond
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = Proxy "requestContext" -> ControllerContext -> RequestContext
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "requestContext" (Proxy "requestContext")
Proxy "requestContext"
#requestContext ?context::ControllerContext
ControllerContext
?context
            Respond
respond Respond -> Respond
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status500 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
title Html
errorMessage))
        Just (exception :: ParamException
exception@(Param.ParamCouldNotBeParsedException { ByteString
$sel:name:ParamNotFoundException :: ParamException -> ByteString
name :: ByteString
name, ByteString
$sel:parserError:ParamNotFoundException :: ParamException -> ByteString
parserError :: ByteString
parserError })) -> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just do
            let (Text
controllerPath, Text
_) = Text -> Text -> (Text, Text)
Text.breakOn Text
":" (ParamException -> Text
forall a. Show a => a -> Text
tshow ParamException
exception)

            let renderParam :: (a, a) -> Html
renderParam (a
paramName, a
paramValue) = [hsx|<li>{paramName}: {paramValue}</li>|]
            let errorMessage :: Html
errorMessage = [hsx|
                    <h2>
                        This exception was caused by a call to <code>param {tshow name}</code> in {tshow controller}.
                    </h2>
                    <p>
                        Here's the error output from the parser: {parserError}
                    </p>

                    <h2>Details</h2>
                    <p style="font-size: 16px">{exception}</p>
                |]



            let title :: Html
title = [hsx|Parameter <q>{name}</q> was invalid|]
            let RequestContext { Respond
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = Proxy "requestContext" -> ControllerContext -> RequestContext
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "requestContext" (Proxy "requestContext")
Proxy "requestContext"
#requestContext ?context::ControllerContext
ControllerContext
?context
            Respond
respond Respond -> Respond
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status500 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
title Html
errorMessage))
        Maybe ParamException
Nothing -> Maybe (IO ResponseReceived)
forall a. Maybe a
Nothing

-- Handler for 'IHP.ModelSupport.RecordNotFoundException'
--
-- Used only in development mode of the app.
recordNotFoundExceptionHandlerDev :: (Show controller, ?context :: ControllerContext) => SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
recordNotFoundExceptionHandlerDev :: SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
recordNotFoundExceptionHandlerDev SomeException
exception controller
controller Text
additionalInfo =
    case SomeException -> Maybe RecordNotFoundException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
        Just (exception :: RecordNotFoundException
exception@(ModelSupport.RecordNotFoundException { $sel:queryAndParams:RecordNotFoundException :: RecordNotFoundException -> (ByteString, [Action])
queryAndParams = (ByteString
query, [Action]
params) })) -> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just do
            let (Text
controllerPath, Text
_) = Text -> Text -> (Text, Text)
Text.breakOn Text
":" (RecordNotFoundException -> Text
forall a. Show a => a -> Text
tshow RecordNotFoundException
exception)
            let errorMessage :: Html
errorMessage = [hsx|
                    <p>
                        The following SQL was executed:
                        <pre class="ihp-error-code">{query}</pre>
                    </p>
                    <p>
                        These query parameters have been used:
                        <pre class="ihp-error-code">{params}</pre>
                    </p>

                    <p>
                        This exception was caused by a call to <code>fetchOne</code> in {tshow controller}.
                    </p>

                    <h2>Possible Solutions:</h2>

                    <p>
                        a) Use <span class="ihp-error-inline-code">fetchOneOrNothing</span>. This will return a <span class="ihp-error-inline-code">Nothing</span>
                        when no results are returned by the database.
                    </p>

                    <p>
                        b) Make sure the the data you are querying is actually there.
                    </p>


                    <h2>Details</h2>
                    <p style="font-size: 16px">{exception}</p>
                |]



            let title :: Html
title = [hsx|Call to fetchOne failed. No records returned.|]
            let RequestContext { Respond
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = Proxy "requestContext" -> ControllerContext -> RequestContext
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "requestContext" (Proxy "requestContext")
Proxy "requestContext"
#requestContext ?context::ControllerContext
ControllerContext
?context
            Respond
respond Respond -> Respond
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status500 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
title Html
errorMessage))
        Maybe RecordNotFoundException
Nothing -> Maybe (IO ResponseReceived)
forall a. Maybe a
Nothing

-- Handler for 'IHP.ModelSupport.RecordNotFoundException'
--
-- Used only in production mode of the app. The exception is handled by calling 'handleNotFound'
recordNotFoundExceptionHandlerProd :: (Show controller, ?context :: ControllerContext) => SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
recordNotFoundExceptionHandlerProd :: SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
recordNotFoundExceptionHandlerProd SomeException
exception controller
controller Text
additionalInfo =
    case SomeException -> Maybe RecordNotFoundException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
        Just (exception :: RecordNotFoundException
exception@(ModelSupport.RecordNotFoundException {})) ->
            let requestContext :: RequestContext
requestContext = Proxy "requestContext" -> ControllerContext -> RequestContext
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "requestContext" (Proxy "requestContext")
Proxy "requestContext"
#requestContext ?context::ControllerContext
ControllerContext
?context
            in
                let ?context = requestContext
                in IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just IO ResponseReceived
(?context::RequestContext) => IO ResponseReceived
handleNotFound
        Maybe RecordNotFoundException
Nothing -> Maybe (IO ResponseReceived)
forall a. Maybe a
Nothing

handleRouterException :: (?context :: RequestContext) => SomeException -> IO ResponseReceived
handleRouterException :: SomeException -> IO ResponseReceived
handleRouterException SomeException
exception = do
    let errorMessage :: Html
errorMessage = [hsx|
            Routing failed with: {tshow exception}

            <h2>Possible Solutions</h2>
            <p>Are you using AutoRoute but some of your fields are not UUID? In that case <a href="https://ihp.digitallyinduced.com/Guide/routing.html#parameter-types" target="_blank">please see the documentation on Parameter Types</a></p>
            <p>Are you trying to do a DELETE action, but your link is missing class="js-delete"?</p>
        |]
    let title :: Html
title = Text -> Html
H.text Text
"Routing failed"
    let RequestContext { Respond
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = ?context::RequestContext
RequestContext
?context
    Respond
respond Respond -> Respond
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status500 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
title Html
errorMessage))

-- | Renders a helpful error when e.g. an UUID value is expected as an action argument, but something else is given
handleInvalidActionArgumentExceptionDev :: (?context :: ControllerContext) => SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
handleInvalidActionArgumentExceptionDev :: SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
handleInvalidActionArgumentExceptionDev SomeException
exception controller
controller Text
additionalInfo = do
    case SomeException -> Maybe InvalidActionArgumentException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
        Just Router.InvalidActionArgumentException { ByteString
$sel:expectedType:InvalidActionArgumentException :: InvalidActionArgumentException -> ByteString
expectedType :: ByteString
expectedType, ByteString
$sel:value:InvalidActionArgumentException :: InvalidActionArgumentException -> ByteString
value :: ByteString
value, ByteString
$sel:field:InvalidActionArgumentException :: InvalidActionArgumentException -> ByteString
field :: ByteString
field } -> do
            let errorMessage :: Html
errorMessage = [hsx|
                    Routing failed with: {tshow exception}

                    <h2>Possible Solutions</h2>
                    <p>Are you using AutoRoute but some of your fields are not UUID? In that case <a href="https://ihp.digitallyinduced.com/Guide/routing.html#parameter-types" target="_blank">please see the documentation on Parameter Types</a></p>
                    <p>Are you trying to do a DELETE action, but your link is missing class="js-delete"?</p>
                |]
            let title :: Html
title = [hsx|Expected <strong>{expectedType}</strong> for field <strong>{field}</strong> but got <q>{value}</q>|]
            let RequestContext { Respond
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = Proxy "requestContext" -> ControllerContext -> RequestContext
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "requestContext" (Proxy "requestContext")
Proxy "requestContext"
#requestContext ?context::ControllerContext
ControllerContext
?context
            IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just (IO ResponseReceived -> Maybe (IO ResponseReceived))
-> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a b. (a -> b) -> a -> b
$ Respond
respond Respond -> Respond
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status400 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
title Html
errorMessage))
        Maybe InvalidActionArgumentException
Nothing -> Maybe (IO ResponseReceived)
forall a. Maybe a
Nothing

handleInvalidActionArgumentExceptionProd :: (?context :: ControllerContext) => SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
handleInvalidActionArgumentExceptionProd :: SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
handleInvalidActionArgumentExceptionProd SomeException
exception controller
controller Text
additionalInfo = do
    case SomeException -> Maybe InvalidActionArgumentException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
        Just Router.InvalidActionArgumentException { ByteString
expectedType :: ByteString
$sel:expectedType:InvalidActionArgumentException :: InvalidActionArgumentException -> ByteString
expectedType, ByteString
value :: ByteString
$sel:value:InvalidActionArgumentException :: InvalidActionArgumentException -> ByteString
value, ByteString
field :: ByteString
$sel:field:InvalidActionArgumentException :: InvalidActionArgumentException -> ByteString
field } -> do
            let title :: Html
title = [hsx|Expected <strong>{expectedType}</strong> for field <strong>{field}</strong>|]
            let RequestContext { Respond
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = Proxy "requestContext" -> ControllerContext -> RequestContext
forall model (name :: Symbol) value.
(KnownSymbol name, HasField name model value) =>
Proxy name -> model -> value
get IsLabel "requestContext" (Proxy "requestContext")
Proxy "requestContext"
#requestContext ?context::ControllerContext
ControllerContext
?context
            IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just (IO ResponseReceived -> Maybe (IO ResponseReceived))
-> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a b. (a -> b) -> a -> b
$ Respond
respond Respond -> Respond
forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> Builder -> Response
responseBuilder Status
status400 [(HeaderName
hContentType, ByteString
"text/html")] (Html -> Builder
Blaze.renderHtmlBuilder (Html -> Html -> Html
forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
title Html
forall a. Monoid a => a
mempty))
        Maybe InvalidActionArgumentException
Nothing -> Maybe (IO ResponseReceived)
forall a. Maybe a
Nothing

renderError :: forall context. (?context :: context, ConfigProvider context) => H.Html -> H.Html -> H.Html
renderError :: Html -> Html -> Html
renderError Html
errorTitle Html
view = Html -> Html
H.docTypeHtml (Html -> Html) -> Attribute -> Html -> Html
forall h. Attributable h => h -> Attribute -> h
! AttributeValue -> Attribute
A.lang AttributeValue
"en" (Html -> Html) -> Html -> Html
forall a b. (a -> b) -> a -> b
$ [hsx|
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/>

    <title>IHP Error</title>
    <style>
        * { -webkit-font-smoothing: antialiased }
        h2 {
            color: white;
            font-size: 1.25rem;
        }
        body {
            margin: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Helvetica Neue", Arial, sans-serif;
        }

        body a {
            color: hsla(196, 13%, 80%, 1);
        }

        .ihp-error-other-solutions {
            margin-top: 2rem;
            padding-top: 0.5rem;
            font-size: 1rem;
            color: hsla(196, 13%, 80%, 1);
            border-top: 1px solid hsla(196, 13%, 60%, 0.4);
        }

        .ihp-error-other-solutions a {
            color: hsla(196, 13%, 80%, 0.9);
            text-decoration: none !important;
            margin-right: 1rem;
            font-size: 0.8rem;
        }
        .ihp-error-other-solutions a:hover {
            color: hsla(196, 13%, 80%, 1);
        }

        .ihp-error-inline-code, .ihp-error-code {
            background-color: rgba(0, 43, 54, 0.5);
            color: white;
            border-radius: 3px;
        }

        .ihp-error-code {
            padding: 1rem;
        }

        .ihp-error-inline-code {
            padding: 3px;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <div style="background-color: #657b83; padding-top: 2rem; padding-bottom: 2rem; color:hsla(196, 13%, 96%, 1)">
        <div style="max-width: 800px; margin-left: auto; margin-right: auto">
            <h1 style="margin-bottom: 2rem; font-size: 2rem; font-weight: 500; border-bottom: 1px solid white; padding-bottom: 0.25rem; border-color: hsla(196, 13%, 60%, 1)">{errorTitle}</h1>
            <div style="margin-top: 1rem; font-size: 1.25rem; color:hsla(196, 13%, 80%, 1)">
                {view}
            </div>

            {when shouldShowHelpFooter helpFooter}
        </div>
    </div>
</body>
    |]
        where
            shouldShowHelpFooter :: Bool
shouldShowHelpFooter = ((FrameworkConfig -> Environment) -> Environment
forall context a.
(?context::context, ConfigProvider context) =>
(FrameworkConfig -> a) -> a
fromConfig FrameworkConfig -> Environment
environment) Environment -> Environment -> Bool
forall a. Eq a => a -> a -> Bool
== Environment
Environment.Development
            helpFooter :: Html
helpFooter = [hsx|
                <div class="ihp-error-other-solutions">
                    <a href="https://stackoverflow.com/questions/tagged/ihp" target="_blank">Ask the IHP Community on StackOverflow</a>
                    <a href="https://github.com/digitallyinduced/ihp/wiki/Troubleshooting" target="_blank">Check the Troubleshooting</a>
                    <a href="https://github.com/digitallyinduced/ihp/issues/new" target="_blank">Open GitHub Issue</a>
                    <a href="https://gitter.im/digitallyinduced/ihp?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge" target="_blank">Gitter</a>
                    <a href="https://www.reddit.com/r/IHPFramework/" target="_blank">Reddit</a>
                </div>
            |]