How to catch sqlite error

I added a miragation prepare to make one of my data field unique but i want to catch that error so I can redirect user or show them error alert on my website instead of letting vapor to handle the error showing part

@mannguyen thereโ€™s no easy answer for this but what you can do is run a catchFlatMap on the save future and parse the error and pass that to the view

1 Like

thank you for answering. Does .save(:on) return an optional object?

No save(on:) returns Future<Model> but that future may fail so you can use a number of methods of handling that failed future

1 Like

would you be so kind and guide me to that section in the book?

So I tried catchMap and it works in my case I just want to leave it here incase someone need it:

func createHandler(_ req: Request) throws -> Future<Response> {
        return try req.content.decode(SubscribeEmail.self).flatMap(to: Response.self) { email in
            return email.save(on: req).map(to: Response.self) { email  in
                guard email.id != nil else {
                    return req.redirect(to: "/?error")
                }
                
                return req.redirect(to: "/?success")
            }.catchMap { error in
                return req.redirect(to: "/?error")
            }
        }
    }

I agree with him on this

@mannguyen Thank you for sharing your solution - much appreciated! :]