Skip to content

Commit ea38fd1

Browse files
committed
feat: handle database errors
Signed-off-by: Muhammad Aaqil <aaqilcs102@gmail.com>
1 parent d1838ad commit ea38fd1

12 files changed

Lines changed: 726 additions & 4 deletions

File tree

‎docs/site/reference/error-codes.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,45 @@ You have the following options how to fix the error
9595
}
9696
```
9797

98+
## Database Error Codes
99+
100+
When repository operations fail due to database constraints, connection issues,
101+
or protocol errors, LoopBack maps low-level database driver errors to
102+
standardized, protocol-neutral error codes.
103+
104+
These domain error codes are automatically mapped to corresponding REST HTTP
105+
statuses by `@loopback/rest`:
106+
107+
| Error Code | HTTP Status | Description |
108+
| :---------------------------- | :----------------------- | :----------------------------------------------------------------------------------------------------------------------------- |
109+
| `UNIQUE_CONSTRAINT_VIOLATION` | 409 Conflict | A record with a duplicate key or non-unique value was inserted or updated. |
110+
| `LOCK_CONFLICT` | 409 Conflict | The operation failed due to a database deadlock or lock wait timeout. |
111+
| `FOREIGN_KEY_VIOLATION` | 422 Unprocessable Entity | The operation violates a foreign key constraint (referencing a non-existent parent or deleting a referenced parent). |
112+
| `NOT_NULL_VIOLATION` | 400 Bad Request | A required non-nullable database column was provided as `null` or omitted without a default value. |
113+
| `CHECK_CONSTRAINT_VIOLATION` | 400 Bad Request | The operation violates a custom SQL `CHECK` constraint. |
114+
| `DATA_TYPE_MISMATCH` | 400 Bad Request | A value provided does not match the database column type (e.g., string length exceeded, invalid string format for field type). |
115+
| `GENERATED_COLUMN_VIOLATION` | 400 Bad Request | An explicit attempt was made to write or update a generated/computed database column. |
116+
| `QUERY_TIMEOUT` | 504 Gateway Timeout | The database query execution exceeded the configured statement timeout threshold. |
117+
| `CONNECTION_FAILURE` | 503 Service Unavailable | The database connection was lost, refused, or unable to be acquired from the pool. |
118+
119+
### Configuring or Disabling Database Error Mapping
120+
121+
By default, `@loopback/rest` automatically translates database domain errors
122+
into HTTP error responses. You can disable this mapping across your application
123+
using `RestBindings.DATABASE_ERROR_MAPPING_OPTIONS`:
124+
125+
```typescript
126+
import {RestBindings} from '@loopback/rest';
127+
128+
// In your application constructor or sequence setup
129+
app.bind(RestBindings.DATABASE_ERROR_MAPPING_OPTIONS).to({
130+
enabled: false,
131+
});
132+
```
133+
134+
When set to `{ enabled: false }`, database errors pass through unmapped and fall
135+
back to the default error handler (returning an HTTP 500 status).
136+
98137
## Other error codes
99138

100139
Besides LoopBack-specific error codes, your application can encounter low-level

‎examples/todo/src/__tests__/helpers.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ export function givenTodo(todo?: Partial<Todo>) {
4848

4949
export const aLocation = {
5050
address: '1 New Orchard Road, Armonk, 10504',
51-
geopoint: <GeoPoint>{y: 41.109728357749, x: -73.72462031805},
51+
geopoint: <GeoPoint>{y: 41.109725723771, x: -73.724620709372},
5252
get geostring() {
5353
return `${this.geopoint.y},${this.geopoint.x}`;
5454
},
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// Copyright IBM Corp. and LoopBack contributors 2019,2020. All Rights Reserved.
2+
// Node module: @loopback/repository
3+
// This file is licensed under the MIT License.
4+
// License text available at https://opensource.org/licenses/MIT
5+
6+
import {expect} from '@loopback/testlab';
7+
8+
import {
9+
CheckConstraintError,
10+
DatabaseConnectionError,
11+
DatabaseError,
12+
DataTypeMismatchError,
13+
ForeignKeyConstraintError,
14+
LockConflictError,
15+
NotNullConstraintError,
16+
UniqueConstraintError,
17+
} from '../../..';
18+
import {handleRepositoryError} from '../../../errors/handle-repository-error';
19+
20+
describe('handleRepositoryError', () => {
21+
it('throws DatabaseError for a falsy error', () => {
22+
expect(() => handleRepositoryError(null)).to.throwError(
23+
new DatabaseError('An unknown database execution error occurred.'),
24+
);
25+
});
26+
27+
it('passes through an existing DatabaseError', () => {
28+
const error = new DatabaseError('Database error');
29+
30+
expect(() => handleRepositoryError(error)).to.throwError(error);
31+
});
32+
33+
it('maps UNIQUE_CONSTRAINT_VIOLATION', () => {
34+
const error = givenConnectorError(
35+
'UNIQUE_CONSTRAINT_VIOLATION',
36+
'Duplicate value',
37+
);
38+
39+
expect(() => handleRepositoryError(error)).to.throwError(
40+
UniqueConstraintError,
41+
);
42+
43+
expect(() => handleRepositoryError(error)).to.throwError(/Duplicate value/);
44+
});
45+
46+
it('maps FOREIGN_KEY_VIOLATION', () => {
47+
const error = givenConnectorError(
48+
'FOREIGN_KEY_VIOLATION',
49+
'Foreign key violation',
50+
);
51+
52+
expect(() => handleRepositoryError(error)).to.throwError(
53+
ForeignKeyConstraintError,
54+
);
55+
});
56+
57+
it('maps NOT_NULL_VIOLATION', () => {
58+
const error = givenConnectorError(
59+
'NOT_NULL_VIOLATION',
60+
'Not-null violation',
61+
);
62+
63+
expect(() => handleRepositoryError(error)).to.throwError(
64+
NotNullConstraintError,
65+
);
66+
});
67+
68+
it('maps CHECK_CONSTRAINT_VIOLATION', () => {
69+
const error = givenConnectorError(
70+
'CHECK_CONSTRAINT_VIOLATION',
71+
'Check constraint violation',
72+
);
73+
74+
expect(() => handleRepositoryError(error)).to.throwError(
75+
CheckConstraintError,
76+
);
77+
});
78+
79+
it('maps DATA_TYPE_MISMATCH', () => {
80+
const error = givenConnectorError(
81+
'DATA_TYPE_MISMATCH',
82+
'Data type mismatch',
83+
);
84+
85+
expect(() => handleRepositoryError(error)).to.throwError(
86+
DataTypeMismatchError,
87+
);
88+
});
89+
90+
it('maps LOCK_CONFLICT', () => {
91+
const error = givenConnectorError('LOCK_CONFLICT', 'Lock conflict');
92+
93+
expect(() => handleRepositoryError(error)).to.throwError(LockConflictError);
94+
});
95+
96+
it('maps CONNECTION_FAILURE', () => {
97+
const error = givenConnectorError(
98+
'CONNECTION_FAILURE',
99+
'Connection failure',
100+
);
101+
102+
expect(() => handleRepositoryError(error)).to.throwError(
103+
DatabaseConnectionError,
104+
);
105+
});
106+
107+
it('preserves message and details when mapping an error', () => {
108+
const details = {
109+
constraint: 'users_email_key',
110+
field: 'email',
111+
};
112+
113+
const error = {
114+
code: 'UNIQUE_CONSTRAINT_VIOLATION',
115+
message: 'Email already exists',
116+
details,
117+
};
118+
119+
try {
120+
handleRepositoryError(error);
121+
} catch (err) {
122+
expect(err).to.be.instanceof(UniqueConstraintError);
123+
expect((err as UniqueConstraintError).message).to.equal(
124+
'Email already exists',
125+
);
126+
expect((err as UniqueConstraintError).details).to.eql(details);
127+
}
128+
});
129+
130+
it('rethrows an unmapped connector error as-is', () => {
131+
const error = {
132+
code: 'SOME_UNKNOWN_ERROR',
133+
message: 'Unknown connector error',
134+
};
135+
136+
try {
137+
handleRepositoryError(error);
138+
} catch (err) {
139+
expect(err).to.equal(error);
140+
}
141+
});
142+
143+
it('rethrows a generic Error as-is', () => {
144+
const error = new Error('Something went wrong');
145+
146+
try {
147+
handleRepositoryError(error);
148+
} catch (err) {
149+
expect(err).to.equal(error);
150+
}
151+
});
152+
153+
it('rethrows an object without a code as-is', () => {
154+
const error = {
155+
message: 'Something went wrong',
156+
};
157+
158+
try {
159+
handleRepositoryError(error);
160+
} catch (err) {
161+
expect(err).to.equal(error);
162+
}
163+
});
164+
});
165+
166+
function givenConnectorError(code: string, message: string) {
167+
return {
168+
code,
169+
message,
170+
details: {
171+
source: 'test',
172+
},
173+
};
174+
}
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// Copyright IBM Corp. and LoopBack contributors 2018,2019. All Rights Reserved.
2+
// Node module: @loopback/repository
3+
// This file is licensed under the MIT License.
4+
// License text available at https://opensource.org/licenses/MIT
5+
6+
/**
7+
* Base abstract class for all database-related domain errors.
8+
* Protocol-neutral: Contains no HTTP status codes or transport metadata.
9+
*/
10+
export class DatabaseError extends Error {
11+
public readonly code: string;
12+
public readonly details?: Record<string, unknown>;
13+
14+
constructor(
15+
message: string,
16+
code = 'DATABASE_ERROR',
17+
details?: Record<string, unknown>,
18+
) {
19+
super(message);
20+
this.name = 'DatabaseError';
21+
this.code = code;
22+
this.details = details;
23+
24+
if (Error.captureStackTrace) {
25+
Error.captureStackTrace(this, this.constructor);
26+
}
27+
}
28+
}
29+
30+
export class UniqueConstraintError extends DatabaseError {
31+
constructor(
32+
message = 'Unique constraint violation occurred.',
33+
details?: Record<string, unknown>,
34+
) {
35+
super(message, 'UNIQUE_CONSTRAINT_VIOLATION', details);
36+
this.name = 'UniqueConstraintError';
37+
}
38+
}
39+
40+
export class ForeignKeyConstraintError extends DatabaseError {
41+
constructor(
42+
message = 'Foreign key constraint violation occurred.',
43+
details?: Record<string, unknown>,
44+
) {
45+
super(message, 'FOREIGN_KEY_VIOLATION', details);
46+
this.name = 'ForeignKeyConstraintError';
47+
}
48+
}
49+
50+
export class NotNullConstraintError extends DatabaseError {
51+
constructor(
52+
message = 'Required property cannot be null or omitted.',
53+
details?: Record<string, unknown>,
54+
) {
55+
super(message, 'NOT_NULL_VIOLATION', details);
56+
this.name = 'NotNullConstraintError';
57+
}
58+
}
59+
60+
export class CheckConstraintError extends DatabaseError {
61+
constructor(
62+
message = 'Check constraint or validation check failed.',
63+
details?: Record<string, unknown>,
64+
) {
65+
super(message, 'CHECK_CONSTRAINT_VIOLATION', details);
66+
this.name = 'CheckConstraintError';
67+
}
68+
}
69+
70+
export class DataTypeMismatchError extends DatabaseError {
71+
constructor(
72+
message = 'Data type mismatch or string truncation occurred.',
73+
details?: Record<string, unknown>,
74+
) {
75+
super(message, 'DATA_TYPE_MISMATCH', details);
76+
this.name = 'DataTypeMismatchError';
77+
}
78+
}
79+
80+
export class LockConflictError extends DatabaseError {
81+
constructor(
82+
message = 'Concurrency lock conflict or deadlock detected.',
83+
details?: Record<string, unknown>,
84+
) {
85+
super(message, 'LOCK_CONFLICT', details);
86+
this.name = 'LockConflictError';
87+
}
88+
}
89+
90+
export class DatabaseConnectionError extends DatabaseError {
91+
constructor(
92+
message = 'Database service connection failed or unavailable.',
93+
details?: Record<string, unknown>,
94+
) {
95+
super(message, 'CONNECTION_FAILURE', details);
96+
this.name = 'DatabaseConnectionError';
97+
}
98+
}
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import {
2+
CheckConstraintError,
3+
DatabaseConnectionError,
4+
DatabaseError,
5+
DataTypeMismatchError,
6+
ForeignKeyConstraintError,
7+
LockConflictError,
8+
NotNullConstraintError,
9+
UniqueConstraintError,
10+
} from './database.error';
11+
import {EntityNotFoundError} from './entity-not-found.error';
12+
13+
/**
14+
* Normalizes or re-throws errors originating from legacy juggler or connector operations.
15+
*/
16+
export function handleRepositoryError(err: unknown): never {
17+
if (!err) {
18+
throw new DatabaseError('An unknown database execution error occurred.');
19+
}
20+
21+
if (err instanceof DatabaseError) {
22+
throw err;
23+
}
24+
25+
if (typeof err === 'object' && err !== null && 'code' in err) {
26+
const errorObj = err as {
27+
code?: string;
28+
message?: string;
29+
details?: Record<string, unknown>;
30+
};
31+
32+
switch (errorObj.code) {
33+
case 'UNIQUE_CONSTRAINT_VIOLATION':
34+
throw new UniqueConstraintError(errorObj.message, errorObj.details);
35+
// returning entity not found error to avoid leaking db schema information
36+
case 'TABLE_NOT_FOUND':
37+
throw new EntityNotFoundError(
38+
errorObj.message || 'record not found',
39+
errorObj.details,
40+
);
41+
case 'FOREIGN_KEY_VIOLATION':
42+
throw new ForeignKeyConstraintError(errorObj.message, errorObj.details);
43+
case 'NOT_NULL_VIOLATION':
44+
throw new NotNullConstraintError(errorObj.message, errorObj.details);
45+
case 'CHECK_CONSTRAINT_VIOLATION':
46+
throw new CheckConstraintError(errorObj.message, errorObj.details);
47+
case 'DATA_TYPE_MISMATCH':
48+
throw new DataTypeMismatchError(errorObj.message, errorObj.details);
49+
case 'LOCK_CONFLICT':
50+
throw new LockConflictError(errorObj.message, errorObj.details);
51+
case 'CONNECTION_FAILURE':
52+
throw new DatabaseConnectionError(errorObj.message, errorObj.details);
53+
}
54+
}
55+
56+
throw err;
57+
}

‎packages/repository/src/errors/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,4 @@ export * from './entity-not-found.error';
77
export * from './invalid-polymorphism.error';
88
export * from './invalid-relation.error';
99
export * from './invalid-body.error';
10+
export * from './database.error';

0 commit comments

Comments
 (0)