{-|
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
, handleRouterException
) where

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

import qualified Text.Blaze.Html5            as H
import qualified Text.Blaze.Html.Renderer.Utf8 as Blaze
import qualified Database.PostgreSQL.Simple as PG
import qualified Data.ByteString.Char8 as ByteString
import qualified Data.ByteString.Lazy as LBS

import IHP.HSX.QQ (hsx)
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 IHP.ApplicationContext
import IHP.Controller.NotFound (handleNotFound)

handleNoResponseReturned :: (Show controller, ?context :: ControllerContext) => controller -> IO ResponseReceived
handleNoResponseReturned :: forall controller.
(Show controller, ?context::ControllerContext) =>
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
respond :: Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond } = ?context::ControllerContext
ControllerContext
?context.requestContext
    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))

displayException :: (Show action, ?context :: ControllerContext, ?applicationContext :: ApplicationContext, ?requestContext :: RequestContext) => SomeException -> action -> Text -> IO ResponseReceived
displayException :: forall action.
(Show action, ?context::ControllerContext,
 ?applicationContext::ApplicationContext,
 ?requestContext::RequestContext) =>
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
            ]

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

    let allHandlers :: [SomeException -> action -> Text -> Maybe (IO ResponseReceived)]
allHandlers = if ?context::ControllerContext
ControllerContext
?context.frameworkConfig.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)]
forall {controller}.
[SomeException
 -> controller -> 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)

    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


    -- Additionally to rendering the error message to the browser we also send it
    -- to the error tracking service (e.g. sentry). Usually this service also writes
    -- the error message to the stderr output
    --
    let exceptionTracker :: Maybe Request -> SomeException -> IO ()
exceptionTracker = ?applicationContext::ApplicationContext
ApplicationContext
?applicationContext.frameworkConfig.exceptionTracker.onException
    let request :: Request
request = ?requestContext::RequestContext
RequestContext
?requestContext.request


    Maybe Request -> SomeException -> IO ()
exceptionTracker (Request -> Maybe Request
forall a. a -> Maybe a
Just Request
request) SomeException
exception

    [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 :: forall controller.
(Show controller, ?context::ControllerContext) =>
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 happened|]

    let (Html
errorMessage, Html
errorTitle) = if ?context::ControllerContext
ControllerContext
?context.frameworkConfig.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
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::ControllerContext
ControllerContext
?context.requestContext

    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 :: forall controller.
(Show controller, ?context::ControllerContext) =>
SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
postgresHandler SomeException
exception controller
controller Text
additionalInfo = do
    let
        handlePostgresOutdatedError :: Show exception => exception -> H.Html -> IO ResponseReceived
        handlePostgresOutdatedError :: forall exception.
Show exception =>
exception -> Html -> IO ResponseReceived
handlePostgresOutdatedError exception
exception Html
errorText = do
            let ihpIdeBaseUrl :: Text
ihpIdeBaseUrl = ?context::ControllerContext
ControllerContext
?context.frameworkConfig.ideBaseUrl
            let title :: Html
title = [hsx|Database looks outdated. {errorText}|]
            let errorMessage :: Html
errorMessage = [hsx|
                        <h2>Possible Solutions</h2>
                        <div style="margin-bottom: 2rem; font-weight: 400;">
                            Have you clicked on
                            <form method="POST" action={ihpIdeBaseUrl <> "/NewMigration"} target="_blank" style="display: inline">
                                <button type="submit">Migrate 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>
                    |]
            let RequestContext { Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::ControllerContext
ControllerContext
?context.requestContext
            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))

        handleSqlError :: ModelSupport.EnhancedSqlError -> IO ResponseReceived
        handleSqlError :: EnhancedSqlError -> IO ResponseReceived
handleSqlError EnhancedSqlError
exception = do
            let ihpIdeBaseUrl :: Text
ihpIdeBaseUrl = ?context::ControllerContext
ControllerContext
?context.frameworkConfig.ideBaseUrl
            let sqlError :: SqlError
sqlError = EnhancedSqlError
exception.sqlError
            let title :: Html
title = [hsx|{sqlError.sqlErrorMsg}|]
            let errorMessage :: Html
errorMessage = [hsx|
                        <h2>While running the following Query:</h2>
                        <div style="margin-bottom: 2rem; font-weight: 400;">
                            <code>{exception.sqlErrorQuery}</code>
                        </div>

                        <h2>With Query Parameters:</h2>
                        <div style="margin-bottom: 2rem; font-weight: 400;">
                            <code>{exception.sqlErrorQueryParams}</code>
                        </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>
                    |]
            let RequestContext { Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::ControllerContext
ControllerContext
?context.requestContext
            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 -> Html -> IO ResponseReceived
forall exception.
Show exception =>
exception -> Html -> IO ResponseReceived
handlePostgresOutdatedError ResultError
exception Html
"The database result does not match the expected type.")
        Maybe ResultError
Nothing -> case SomeException -> Maybe EnhancedSqlError
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
            -- Catching  `relation "..." does not exist`
            Just exception :: EnhancedSqlError
exception@ModelSupport.EnhancedSqlError { SqlError
sqlError :: SqlError
$sel:sqlError:EnhancedSqlError :: EnhancedSqlError -> SqlError
sqlError }
                |  ByteString
"relation" ByteString -> ByteString -> Bool
`ByteString.isPrefixOf` (SqlError
sqlError.sqlErrorMsg)
                Bool -> Bool -> Bool
&& ByteString
"does not exist" ByteString -> ByteString -> Bool
`ByteString.isSuffixOf` (SqlError
sqlError.sqlErrorMsg)
                -> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just (EnhancedSqlError -> Html -> IO ResponseReceived
forall exception.
Show exception =>
exception -> Html -> IO ResponseReceived
handlePostgresOutdatedError EnhancedSqlError
exception Html
"A table is missing.")

            -- Catching  `columns "..." does not exist`
            Just exception :: EnhancedSqlError
exception@ModelSupport.EnhancedSqlError { SqlError
$sel:sqlError:EnhancedSqlError :: EnhancedSqlError -> SqlError
sqlError :: SqlError
sqlError }
                |  ByteString
"column" ByteString -> ByteString -> Bool
`ByteString.isPrefixOf` (SqlError
sqlError.sqlErrorMsg)
                Bool -> Bool -> Bool
&& ByteString
"does not exist" ByteString -> ByteString -> Bool
`ByteString.isSuffixOf` (SqlError
sqlError.sqlErrorMsg)
                -> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just (EnhancedSqlError -> Html -> IO ResponseReceived
forall exception.
Show exception =>
exception -> Html -> IO ResponseReceived
handlePostgresOutdatedError EnhancedSqlError
exception Html
"A column is missing.")
            -- Catching other SQL Errors
            Just EnhancedSqlError
exception -> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just (EnhancedSqlError -> IO ResponseReceived
handleSqlError EnhancedSqlError
exception)
            Maybe EnhancedSqlError
Nothing -> Maybe (IO ResponseReceived)
forall a. Maybe a
Nothing

patternMatchFailureHandler :: (Show controller, ?context :: ControllerContext) => SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
patternMatchFailureHandler :: forall controller.
(Show controller, ?context::ControllerContext) =>
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
_) = HasCallStack => Text -> Text -> (Text, 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
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::ControllerContext
ControllerContext
?context.requestContext
            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 :: forall controller.
(Show controller, ?context::ControllerContext) =>
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
_) = HasCallStack => Text -> Text -> (Text, 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
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::ControllerContext
ControllerContext
?context.requestContext
            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
name :: ByteString
$sel:name:ParamNotFoundException :: ParamException -> ByteString
name, ByteString
parserError :: ByteString
$sel:parserError:ParamNotFoundException :: ParamException -> ByteString
parserError })) -> IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just do
            let (Text
controllerPath, Text
_) = HasCallStack => Text -> Text -> (Text, 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
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::ControllerContext
ControllerContext
?context.requestContext
            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 :: forall controller.
(Show controller, ?context::ControllerContext) =>
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
_) = HasCallStack => Text -> Text -> (Text, 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
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::ControllerContext
ControllerContext
?context.requestContext
            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 :: (?context :: ControllerContext) => SomeException -> controller -> Text -> Maybe (IO ResponseReceived)
recordNotFoundExceptionHandlerProd :: forall controller.
(?context::ControllerContext) =>
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 = ?context::ControllerContext
ControllerContext
?context.requestContext
            in
                let ?context = ?context::RequestContext
RequestContext
requestContext
                in IO ResponseReceived -> Maybe (IO ResponseReceived)
forall a. a -> Maybe a
Just (Request -> Respond -> IO ResponseReceived
handleNotFound ?context::RequestContext
RequestContext
?context.request ?context::RequestContext
RequestContext
?context.respond)
        Maybe RecordNotFoundException
Nothing -> Maybe (IO ResponseReceived)
forall a. Maybe a
Nothing

handleRouterException :: (?context :: RequestContext) => SomeException -> IO ResponseReceived
handleRouterException :: (?context::RequestContext) => SomeException -> IO ResponseReceived
handleRouterException SomeException
exception =
    case SomeException -> Maybe TypedAutoRouteError
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
        Just Router.NoConstructorMatched { ByteString
expectedType :: ByteString
$sel:expectedType:BadType :: TypedAutoRouteError -> ByteString
expectedType, Maybe ByteString
value :: Maybe ByteString
$sel:value:BadType :: TypedAutoRouteError -> Maybe ByteString
value, ByteString
field :: ByteString
$sel:field:BadType :: TypedAutoRouteError -> ByteString
field } -> do
            let errorMessage :: Html
errorMessage = [hsx|
                    <p>Routing failed with: {tshow exception}</p>

                    <h2>Possible Solutions</h2>
                    <p>You can pass this parameter by appending <code>&{field}=someValue</code> to the URL.</p>
                |]
            let title :: Html
title = case Maybe ByteString
value of
                    Just ByteString
value -> [hsx|Expected <strong>{expectedType}</strong> for field <strong>{field}</strong> but got <q>{value}</q>|]
                    Maybe ByteString
Nothing -> [hsx|The action was called without the required <q>{field}</q> parameter|]
            let RequestContext { Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::RequestContext
RequestContext
?context
            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))
        Just Router.BadType { ByteString
$sel:expectedType:BadType :: TypedAutoRouteError -> ByteString
expectedType :: ByteString
expectedType, $sel:value:BadType :: TypedAutoRouteError -> Maybe ByteString
value = Just ByteString
value, ByteString
$sel:field:BadType :: TypedAutoRouteError -> ByteString
field :: ByteString
field } -> do
            let errorMessage :: Html
errorMessage = [hsx|
                    <p>Routing failed with: {tshow exception}</p>
                |]
            let title :: Html
title = [hsx|Query parameter <q>{field}</q> needs to be a <q>{expectedType}</q> but got <q>{value}</q>|]
            let RequestContext { Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::RequestContext
RequestContext
?context
            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 TypedAutoRouteError
_ -> case SomeException -> Maybe UnexpectedMethodException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
exception of
            Just Router.UnexpectedMethodException { $sel:allowedMethods:UnexpectedMethodException :: UnexpectedMethodException -> [StdMethod]
allowedMethods = [StdMethod
Router.DELETE], $sel:method:UnexpectedMethodException :: UnexpectedMethodException -> StdMethod
method = StdMethod
Router.GET } -> do
                let Text
exampleLink :: Text = Text
"<a href={DeleteProjectAction} class=\"js-delete\">Delete Project</a>"
                let Text
formExample :: Text = String -> Text
forall a b. ConvertibleStrings a b => a -> b
cs [plain|
<form method="POST" action={DeleteProjectAction}>
    <input type="hidden" name="_method" value="DELETE"/>
    <button type="submit">Delete Project</button>
</form>
                |]
                let errorMessage :: Html
errorMessage = [hsx|
                        <p>
                            You cannot directly link to Delete Action.
                            GET requests should not have any external side effects, as a user could accidentally trigger it by following a normal link.
                        </p>

                        <h2>Possible Solutions</h2>
                        <p>
                            a) Add a <code>js-delete</code> class to your link. IHP's helper.js will intercept link clicks on these links and use a form with a DELETE request to submit the request.
                            <br /><br/>

                            Example: <br /><br />
                            <code>{exampleLink}</code>
                        </p>
                        <p>
                            b) Use a form to submit the request as a DELETE request:
                            <br /><br/>

                            Example: <br />
                            <pre>{formExample}</pre>
                            HTML forms don't support DELETE requests natively, therefore we use the hidden input field to work around this browser limitation.
                        </p>
                    |]
                let title :: Html
title = [hsx|Action was called from a GET request, but needs to be called as a DELETE request|]
                let RequestContext { Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::RequestContext
RequestContext
?context
                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))
            Just Router.UnexpectedMethodException { $sel:allowedMethods:UnexpectedMethodException :: UnexpectedMethodException -> [StdMethod]
allowedMethods = [StdMethod
Router.POST], $sel:method:UnexpectedMethodException :: UnexpectedMethodException -> StdMethod
method = StdMethod
Router.GET } -> do
                let errorMessage :: Html
errorMessage = [hsx|
                        <p>
                            You cannot directly link to Create Action.
                            GET requests should not have any external side effects, as a user could accidentally trigger it by following a normal link.
                        </p>

                        <h2>Possible Solutions</h2>
                        <p>
                            <a style="text-decoration: none" href="https://ihp.digitallyinduced.com/Guide/form.html" target="_blank">Make a form with <code>formFor</code> to do the request</a>
                        </p>
                    |]
                let title :: Html
title = [hsx|Action was called from a GET request, but needs to be called as a POST request|]
                let RequestContext { Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::RequestContext
RequestContext
?context
                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))
            Just Router.UnexpectedMethodException { [StdMethod]
$sel:allowedMethods:UnexpectedMethodException :: UnexpectedMethodException -> [StdMethod]
allowedMethods :: [StdMethod]
allowedMethods, StdMethod
$sel:method:UnexpectedMethodException :: UnexpectedMethodException -> StdMethod
method :: StdMethod
method } -> do
                let errorMessage :: Html
errorMessage = [hsx|
                        <p>Routing failed with: {tshow exception}</p>
                        <h2>Possible Solutions</h2>
                        <p>
                            <a style="text-decoration: none" href="https://ihp.digitallyinduced.com/Guide/form.html" target="_blank">Make a form with <code>formFor</code> to do the request</a>
                        </p>
                    |]
                let title :: Html
title = [hsx|Action was called with a {method} request, but needs to be called with one of these request methods: <q>{allowedMethods}</q>|]
                let RequestContext { Respond
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: Respond
respond } = ?context::RequestContext
RequestContext
?context
                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 UnexpectedMethodException
_ -> do
                let errorMessage :: Html
errorMessage = [hsx|
                        Routing failed with: {tshow exception}

                        <h2>Possible Solutions</h2>
                        <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
$sel:respond:RequestContext :: RequestContext -> Respond
respond :: 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))


renderError :: forall context. (?context :: context, ConfigProvider context) => H.Html -> H.Html -> H.Html
renderError :: forall context.
(?context::context, ConfigProvider context) =>
Html -> Html -> Html
renderError Html
errorTitle Html
view = [hsx|
<!DOCTYPE html>
<html lang="en">
    <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;
                overflow-x: auto;
            }

            .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>
</html>
    |]
        where
            shouldShowHelpFooter :: Bool
shouldShowHelpFooter = context
?context::context
?context.frameworkConfig.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://ihp.digitallyinduced.com/Slack" target="_blank">Slack</a>
                    <a href="https://www.reddit.com/r/IHPFramework/" target="_blank">Reddit</a>
                    <a href="https://stackshare.io/ihp" target="_blank">StackShare</a>
                </div>
            |]