Skip to content

How to customize the JSON content of HTTP error responses #1867

@hbakhtiyor

Description

@hbakhtiyor

for example

// src/controllers/hello.controller.ts
import {HelloRepository} from '../repositories';
import {HelloMessage} from '../models';
import {get, param, HttpErrors} from '@loopback/rest';
import {repository} from '@loopback/repository';

export class HelloController {
  constructor(@repository(HelloRepository) protected repo: HelloRepository) {}

  // returns a list of our objects
  @get('/messages')
  async list(@param.query.number('limit') limit = 10): Promise<HelloMessage[]> {
    // throw an error when the parameter is not a non-positive integer
    if (!Number.isInteger(limit) || limit < 1) {
      throw new HttpErrors.UnprocessableEntity('limit is non-positive');
    } else if (limit > 100) {
      limit = 100;
    }
    return await this.repo.find({limit});
  }
}

invalid fields will result in a 422 unprocessable entity response with json body.

{
  "message": "Validation Failed",
  "errors": [
    {
      "resource": "Hello",
      "field": "limit",
      "code": "non_positive"
    }
  ]
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    DocsRESTIssues related to @loopback/rest package and REST transport in generaluser request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions