her icon indicating copy to clipboard operation
her copied to clipboard

Adding custom errors to a model based on server response

Open samstarling opened this issue 7 years ago • 2 comments

Hi @zacharywelch @edtjones – I've written some middleware to try and handle custom errors, but I can't seem to get it to work, because I'm not sure what the format of env[:body][:errors] should be:

class MyErrorMiddleware < Her::Middleware::DefaultParseJSON
  def on_complete(env)
    if env[:status] == 400
      super
      env[:body][:errors] = ["Hello"] # in reality, parse errors
    else
      super
    end
  end
end

The API returns something like this:

{
  errorCode: 123
  errorText: "INVALID_OPERATION"
}

When I use the above middleware, I don't get any errors in the ActiveModel::Errors object on my model.errors, but I do see the response JSON showing up in it's @base variable when I call .errors.inspect. Am I doing something wrong?

samstarling avatar Feb 02 '18 15:02 samstarling

You could try following #101 and see if that helps. The method's been renamed as store_response_errors

zacharywelch avatar Feb 02 '18 19:02 zacharywelch

@zacharywelch Thanks – I'll have a read. Is it possible to use store_response_errors with validates? I have some basic "presence" validations on my model, but I also want to be able to handle errors from the API in a custom manner.

samstarling avatar Feb 08 '18 11:02 samstarling