hapijs / hapijs/joi

Custom error context with references

Open
#3,036 0 comments 0 reactions 0 assignees View on GitHub
support
Dominant language
JavaScript
Stars
21.2k
Forks
1.5k
Avg merge
4h 57m
Merged PRs (30d)
14

Description

### Runtime

node.js

### Runtime version

20

### Module version

17.13

### Used with

standalone

### Any other relevant information

_No response_

### How can we help?

I would like to add custom properties to the `context` object of the returned error.

Given the following schema:

```js
const projectSchema = object.keys({
id: number.required(),
description: string.required(),
records: array.items(object.keys({
id: number.required(),
title: string.required(),
})).min(2).required()
})
```

I would like to automatically annotate the returned errors with their respective parents' ID. e.g.

```
[
{
message: '"description" is not allowed to be empty',
path: [ 'description' ],
type: 'description.empty',
context: {
**projectId: 12**
label: 'title',
value: '',
key: 'title'
},
{
message: '"title" is not allowed to be empty',
path: ['records', '0', 'title' ],
type: 'string.empty',
context: {
**recordId: 21**
**projectId: 12**
label: 'title',
value: '',
key: 'title'
}
]
```
I've tried something like this already but doesn't seem to be working:

```js
title: string
.error((err) => {
err.forEach((err) => {
err.local.msg = Joi.ref('id')
})
return err
})
.required(),
```

Thank you!

Contributor guide

Open the contributing guide

Research direction

The issue does not name any source files, tests, or entry points. Start by locating Joi's validation error and context-generation APIs, then clarify how parent references should be resolved and whether the behavior belongs in schema definitions or error customization; done means nested errors consistently include the requested parent IDs.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, node.js
Domain
backend-api-design
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.