diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb index 11bd28b7a..74deb686b 100644 --- a/app/controllers/users_controller.rb +++ b/app/controllers/users_controller.rb @@ -19,7 +19,10 @@ class UsersController < ApplicationController format.json { head :no_content } end else - render :edit, status: :unprocessable_entity + respond_to do |format| + format.html { render :edit, status: :unprocessable_entity } + format.json { render json: @user.errors, status: :unprocessable_entity } + end end end diff --git a/docs/API.md b/docs/API.md index 47473a845..107521596 100644 --- a/docs/API.md +++ b/docs/API.md @@ -83,6 +83,29 @@ else end ``` +## Error Responses + +When a request fails, the API response will communicate the source of the problem through the HTTP status code. + +| Status Code | Description | +|-------------|-------------| +| `400 Bad Request` | The request was malformed or missing required parameters | +| `401 Unauthorized` | Authentication failed or access token is invalid | +| `403 Forbidden` | You don't have permission to perform this action | +| `404 Not Found` | The requested resource doesn't exist or you don't have access to it | +| `422 Unprocessable Entity` | Validation failed (see error response format above) | +| `500 Internal Server Error` | An unexpected error occurred on the server | + +If a request contains invalid data for fields, such as entering a string into a number field, in most cases the API will respond with a `500 Internal Server Error`. Clients are expected to perform some validation on their end before making a request. + +Validation error will produce a `422 Unprocessable Entity` which will sometimes be accompanied by details about the validation errors: + +```json +{ + "avatar": ["must be a JPEG, PNG, GIF, or WebP image"] +} +``` + ## Pagination All endpoints that return a list of items are paginated. The page size can vary from endpoint to endpoint, diff --git a/test/controllers/users_controller_test.rb b/test/controllers/users_controller_test.rb index bf6854a0d..20008dcee 100644 --- a/test/controllers/users_controller_test.rb +++ b/test/controllers/users_controller_test.rb @@ -112,6 +112,17 @@ class UsersControllerTest < ActionDispatch::IntegrationTest assert_equal "New David", users(:david).reload.name end + test "update as JSON with invalid avatar returns errors" do + sign_in_as :kevin + + svg_file = fixture_file_upload("avatar.svg", "image/svg+xml") + + put user_path(users(:kevin), format: :json), params: { user: { avatar: svg_file } } + + assert_response :unprocessable_entity + assert @response.parsed_body["avatar"].present? + end + test "destroy as JSON" do sign_in_as :kevin