Marta
Marta

Reputation: 1162

F# catch System.Web.Exception

I have written tests with TickSpec (F# version of C# Specflow) to test a web service. When I run the test where I expect the response to come with a 200 OK all is fine. When I intentionally send an incorrect request I receive a 400 Bad Request, but the test fails, although 400 is what I want to get back. So the question is - how do I catch an exception and continue in F#?

This is a snippet of code I have:

let sendRequest(requestBody : HttpRequestBody) = 
    let response = Http.Request(url, headers = requestHeaders, body = requestBody)
    let responseStatusCode = response.StatusCode
    let extractedResponseData = 
    // code here to extract data from response
(responseStatusCode, extractedResponseData)

The error I am getting is

System.Net.WebException : The remote server returned an error: (400) Bad Request.

I was hoping that putting a try catch (try with in F#?) around the

 let response = Http.Request(url, headers = requestHeaders, body = requestBody)

would solve the problem.

Can I do that and how do I do it?

Upvotes: 1

Views: 511

Answers (1)

Marta
Marta

Reputation: 1162

Adding:

   silentHttpErrors = true

to:

   let response

as in:

 let response = Http.Request(url, headers = requestHeaders, body = requestBody, silentHttpErrors = true)

sorted the problem. Now the tests ignore the System.Net.WebException and I can test the application for behavior related to a 400 bad request.

More here: http://fsharp.github.io/FSharp.Data/library/Http.html

Upvotes: 3

Related Questions