Server Side Error Handling

I worked out this method of server-side error displaying last night in my app, and I thought I might share it and see if anyone else had other solutions :smile:

Basically I’m expecting a JSON object that looks like:

{
  errors: {
    email: ["can't be blank"],
    password: ["doesn't match confirmation"]
  }
}

To handle it, I’m doing three things:

  1. Binding the form control-group divs to a computed property called hasFieldErrors for an error css class
  2. Binding the actual error content to an output computed property
  3. Assigning the returned errors to a property that the other computed properties depend on

My controller looks like this:

App.RegistrationController = Ember.Controller.extend
  email: null
  password: null
  passwordConfirmation: null
  emailErrors: []
  passwordErrors: []

  hasEmailErrors: Ember.computed.notEmpty('emailErrors')
  hasPasswordErrors: Ember.computed.notEmpty('passwordErrors')

  emailErrorOutput: (->
    output = "Email "
    for error in @emailErrors
      output = "#{output} #{error}"
  ).property('emailErrors')

  passwordErrorOutput: (->
    output = "Password "
    for error in @passwordErrors
      output = "#{output} #{error}"
  ).property('passwordErrors')

  sendRegistration: () ->
    self = @
    self.set('emailErrors', null)
    self.set('passwordErrors', null)
    $.post('/users', 
      user:
        email: @email,
        password: @password,
        password_confirmation: @passwordConfirmation)
    .done (response) ->
      App.Auth.createSession(response)
    .fail (response) ->
      errors = response.responseJSON.errors
      if errors.email
        self.set('emailErrors', errors.email)
      if errors.password
        self.set('passwordErrors', errors.password)

I’m pretty happy with this. How are others handling server side errors?

1 Like

I’m looking for a good pattern for server side errors and appreciate you sharing this. This seems like a good approach for a model with only a few fields, but my model has a ton of fields. I wonder if there is a more dry way of writing this?

Also, my handlebars templates are looking pretty nasty…