theam / aws-lambda-haskell-runtime

⚡Haskell runtime for AWS Lambda
https://theam.github.io/aws-lambda-haskell-runtime/
Other
270 stars 48 forks source link

Way to return an error as json #42

Closed jacobstanley closed 5 years ago

jacobstanley commented 5 years ago

Current only a String can be returned on the left, this would be fine except it goes via toJSON so if you already have json then it's double encoded.

If it there was a way to pass the string through untouched (not going via toJSON) as with LambdaResult that would be great.

NickSeagull commented 5 years ago

The idea is that you would define your own data type for error handling, and use it on the left. Like so:

data Err = Err
  { reason :: Text
  , code :: Int
  } deriving (Generic, ToJSON)

handler :: String -> Context -> IO (Either Err Int)
handler someText _ =
  pure (Left "Not found" 404)

This would handle the conversion to a JSON automatically.

If I understood you correctly, what you want is a way of working with a JSON string and then return it as it is?

Perhaps we could introduce a newtype to make Aeson skip the conversion to a JSON string?

jacobstanley commented 5 years ago

Oh if the above is possible then that solves my problem already! So I just need a type which supports ToJSON ? Apologies I inferred that the Left had to be a String.

NickSeagull commented 5 years ago

If I recall correctly, that is supported yeah :)

No need to apologize, if you inferred that, it means that the documentation is not clear enough 😅

NickSeagull commented 5 years ago

I just checked the docs, and in fact it is documented 😅 in the Adding a Handler :

The output will always be an IO (Either errorType resultType) where

  • errorType is whatever custom error type you want to use.
  • resultType is what your function will return if everything goes well. Note that both types must implement ToJSON, as the runtime will use it to serialize the values.

Closing this, feel free to reopen if you have more questions 😁