Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

purescript - Why does using try in conjuntion with affjax's XHRError result in a mismatch on the Error type?

I'd like to be able to catch communications errors when using affjax in purescript. I try it like this:

module Main where

import Prelude

import Affjax as AX
import Affjax.ResponseFormat as ResponseFormat
import Data.Argonaut.Core (stringify, fromString)
import Data.Either (Either(..))
import Data.HTTP.Method (Method(..))
import Effect.Aff (launchAff)
import Effect.Class.Console (log)

import Effect.Exception(message)
import Control.Monad.Error.Class (try)


main = void $ launchAff $ do
  resultEi <- try $ AX.get ResponseFormat.string "/api"
  let result = case resultEi of
        Left err -> Left $ AX.XHRError err
        rightRes@(Right _)-> rightRes
  case result of
    Left err -> log $ "GET /api response failed to decode: " <> AX.printError err
    Right response -> log $ "GET /api response: " <> response.body

This results in the somewhat confusing error, particularly so because I'm not really sure what would be here other than Effect.Exception.Error since both Aff and XHRError seem to use this Error datatype.

Error 1 of 1

  Could not match type

    Error

  with type

    Error


while trying to match type Either Error
  with type Either Error
while checking that expression rightRes
  has type t0
in value declaration main

where t0 is an unknown type
question from:https://stackoverflow.com/questions/65920196/why-does-using-try-in-conjuntion-with-affjaxs-xhrerror-result-in-a-mismatch-on

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The branches of your case have different types.

The Left branch has type Either Effect.Exception.Error a, because that's how you construct it.

But your Right branch has the same type as rightRes, because that's what you're returning from it, and that type is Either Affjax.Error (Response _).

So the types don't match.

To make them match, you have to unwrap rightRes and rewrap it again:

let result = case resultEi of
      Left err -> Left $ AX.XHRError err
      Right res -> Right res

Yes, it will have the exact same content, but the type will be different.


But if your intent is just to change the type of the error, then I'd recommend lmap from Bifunctor:

let result = lmap AX.XHRError resultEi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...