Recipes

Validation issues

Although field validation issues aren’t part of the specs, they are often used by frameworks or apis in combination with the 422 status code (HttpUnprocessableEntity). For convenience, it’s possible to directly attach them to the exception. That allows to easily access them in an error handler (ie: json-api errors…). Be aware that for simple request validation the 400 status code is more appropriate (one message).

import { HttpUnprocessableEntity } from '@httpx/exception';
 
const e422 = new HttpUnprocessableEntity({
  issues: [
    {
      message: 'Invalid email',
      path: 'email',
      code: 'invalid_email',
    },
    {
      message: 'Invalid address',
      path: ['addresses', 0, 'line1'],
      code: 'empty_string',
    },
  ],
});
 
console.log(e422.issues);

For reference, see github api, rails or api-plaform.