#Throwing Abort() on server is received on client with a nil error

1 messages · Page 1 of 1 (latest)

hot marlin
#

Hello,

My controller function is throwing like so:

throw Abort(.badRequest, reason: "\(error)")

On the client, where the response is received:

let task = URLSession.shared.dataTask(with: request) { _, response, error in

The error is nil and the response status is 400 (correct). I'm surprised that the error is nil. Is this expected? And if so, how would I return the reason or message from the server?

Thanks!

quartz crest
#

Errors delivered by URLSession callbacks only cover actual connection-level errors; the 400 Bad Request status is considered an "application"-level error (where the "application" is HTTP). To detect these failures, you need to look at the response (in particular, by casting it via response as? HTTPURLResponse) and check its statusCode for the status you expect (most often 200 OK, but depending on the route you're invoking, 201 Created or 204 No Content, for example, might also be valid).

#

The actual error text, assuming you're using the default ErrorMiddleware, will be part of the response body, which is still provided in the case of HTTP-level errors.

hot marlin
#

Ugh. It's passed as a body in the response:

#
(lldb) po String(data: data!, encoding: .utf8)
▿ Optional<String>
  - some : "{\"error\":true,\"reason\":\"typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: \\\"date\\\", intValue: nil)], debugDescription: \\\"Expected to decode String but found a number instead.\\\", underlyingError: nil))\"}"
#

Cool.

quartz crest
#

Bonus chatter: That body JSON is produced by the aforementioned default ErrorMiddleware in Vapor; if you'd prefer to receive error response bodies in a different format, you can add your own error-handling middleware (see the implementation of ErrorMiddleware for examples of how to do this).

hot marlin
#

Perfect. It's fine like this. Just wanted to understand the error situation. As always, thanks Gwynne for the help!

quartz crest
#

As (also) always, my pleasure!