Skip to content

Commit d873f2c

Browse files
committed
feat: add more cases
Signed-off-by: Muhammad Aaqil <aaqilcs102@gmail.com>
1 parent ea38fd1 commit d873f2c

6 files changed

Lines changed: 201 additions & 10 deletions

File tree

‎packages/repository/src/__tests__/unit/errors/database-driver-error.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,17 @@ import {expect} from '@loopback/testlab';
77

88
import {
99
CheckConstraintError,
10+
ColumnNotFoundError,
1011
DatabaseConnectionError,
1112
DatabaseError,
1213
DataTypeMismatchError,
1314
ForeignKeyConstraintError,
15+
GeneratedColumnViolationError,
1416
LockConflictError,
1517
NotNullConstraintError,
18+
QueryTimeoutError,
19+
DbSyntaxError,
20+
EntityNotFoundError,
1621
UniqueConstraintError,
1722
} from '../../..';
1823
import {handleRepositoryError} from '../../../errors/handle-repository-error';
@@ -76,6 +81,33 @@ describe('handleRepositoryError', () => {
7681
);
7782
});
7883

84+
it('maps TABLE_NOT_FOUND', () => {
85+
const error = givenConnectorError('TABLE_NOT_FOUND', 'Entity not found');
86+
87+
expect(() => handleRepositoryError(error)).to.throwError(
88+
EntityNotFoundError,
89+
);
90+
});
91+
92+
it('maps COLUMN_NOT_FOUND', () => {
93+
const error = givenConnectorError('COLUMN_NOT_FOUND', 'Column not found');
94+
95+
expect(() => handleRepositoryError(error)).to.throwError(
96+
ColumnNotFoundError,
97+
);
98+
});
99+
100+
it('maps GENERATED_COLUMN_VIOLATION', () => {
101+
const error = givenConnectorError(
102+
'GENERATED_COLUMN_VIOLATION',
103+
'Generated column violation',
104+
);
105+
106+
expect(() => handleRepositoryError(error)).to.throwError(
107+
GeneratedColumnViolationError,
108+
);
109+
});
110+
79111
it('maps DATA_TYPE_MISMATCH', () => {
80112
const error = givenConnectorError(
81113
'DATA_TYPE_MISMATCH',
@@ -87,6 +119,16 @@ describe('handleRepositoryError', () => {
87119
);
88120
});
89121

122+
it('maps SYNTAX_ERROR', () => {
123+
const error = givenConnectorError('SyntaxError', 'Syntax error');
124+
expect(() => handleRepositoryError(error)).to.throwError(DbSyntaxError);
125+
});
126+
127+
it('maps QUERY_TIMEOUT', () => {
128+
const error = givenConnectorError('QUERY_TIMEOUT', 'Query timeout');
129+
expect(() => handleRepositoryError(error)).to.throwError(QueryTimeoutError);
130+
});
131+
90132
it('maps LOCK_CONFLICT', () => {
91133
const error = givenConnectorError('LOCK_CONFLICT', 'Lock conflict');
92134

‎packages/repository/src/errors/database.error.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,36 @@ export class CheckConstraintError extends DatabaseError {
6767
}
6868
}
6969

70+
export class TableNotFoundError extends DatabaseError {
71+
constructor(
72+
message = 'The requested database table or relation does not exist.',
73+
details?: Record<string, unknown>,
74+
) {
75+
super(message, 'TABLE_NOT_FOUND', details);
76+
this.name = 'TableNotFoundError';
77+
}
78+
}
79+
80+
export class ColumnNotFoundError extends DatabaseError {
81+
constructor(
82+
message = 'The requested database column does not exist.',
83+
details?: Record<string, unknown>,
84+
) {
85+
super(message, 'COLUMN_NOT_FOUND', details);
86+
this.name = 'ColumnNotFoundError';
87+
}
88+
}
89+
90+
export class GeneratedColumnViolationError extends DatabaseError {
91+
constructor(
92+
message = 'Cannot manually assign or update values on a database-generated computed column.',
93+
details?: Record<string, unknown>,
94+
) {
95+
super(message, 'GENERATED_COLUMN_VIOLATION', details);
96+
this.name = 'GeneratedColumnViolationError';
97+
}
98+
}
99+
70100
export class DataTypeMismatchError extends DatabaseError {
71101
constructor(
72102
message = 'Data type mismatch or string truncation occurred.',
@@ -87,6 +117,26 @@ export class LockConflictError extends DatabaseError {
87117
}
88118
}
89119

120+
export class QueryTimeoutError extends DatabaseError {
121+
constructor(
122+
message = 'The database operation took too long and was aborted.',
123+
details?: Record<string, unknown>,
124+
) {
125+
super(message, 'QUERY_TIMEOUT', details);
126+
this.name = 'QueryTimeoutError';
127+
}
128+
}
129+
130+
export class DbSyntaxError extends DatabaseError {
131+
constructor(
132+
message = 'A database syntax or parse error occurred.',
133+
details?: Record<string, unknown>,
134+
) {
135+
super(message, 'SYNTAX_ERROR', details);
136+
this.name = 'DbSyntaxError';
137+
}
138+
}
139+
90140
export class DatabaseConnectionError extends DatabaseError {
91141
constructor(
92142
message = 'Database service connection failed or unavailable.',

‎packages/repository/src/errors/handle-repository-error.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
import {
22
CheckConstraintError,
3+
ColumnNotFoundError,
34
DatabaseConnectionError,
45
DatabaseError,
56
DataTypeMismatchError,
7+
DbSyntaxError,
68
ForeignKeyConstraintError,
9+
GeneratedColumnViolationError,
710
LockConflictError,
811
NotNullConstraintError,
12+
QueryTimeoutError,
913
UniqueConstraintError,
1014
} from './database.error';
1115
import {EntityNotFoundError} from './entity-not-found.error';
@@ -50,6 +54,17 @@ export function handleRepositoryError(err: unknown): never {
5054
throw new LockConflictError(errorObj.message, errorObj.details);
5155
case 'CONNECTION_FAILURE':
5256
throw new DatabaseConnectionError(errorObj.message, errorObj.details);
57+
case 'COLUMN_NOT_FOUND':
58+
throw new ColumnNotFoundError(errorObj.message, errorObj.details);
59+
case 'GENERATED_COLUMN_VIOLATION':
60+
throw new GeneratedColumnViolationError(
61+
errorObj.message,
62+
errorObj.details,
63+
);
64+
case 'SyntaxError':
65+
throw new DbSyntaxError(errorObj.message, errorObj.details);
66+
case 'QUERY_TIMEOUT':
67+
throw new QueryTimeoutError(errorObj.message, errorObj.details);
5368
}
5469
}
5570

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1-
import {UniqueConstraintError} from '@loopback/repository';
1+
import {
2+
UniqueConstraintError,
3+
QueryTimeoutError,
4+
TableNotFoundError,
5+
DatabaseConnectionError,
6+
} from '@loopback/repository';
27
import {Client, createRestAppClient, expect} from '@loopback/testlab';
38
import {get, RestApplication, RestBindings} from '../..';
49

@@ -7,10 +12,25 @@ describe('RejectProvider - DATABASE_ERROR_MAPPING_OPTIONS', () => {
712
let client: Client;
813

914
class TestController {
10-
@get('/test-db-error')
11-
testDbError() {
15+
@get('/test-unique-error')
16+
testUniqueError() {
1217
throw new UniqueConstraintError('Duplicate key error');
1318
}
19+
20+
@get('/test-timeout-error')
21+
testTimeoutError() {
22+
throw new QueryTimeoutError('Query timed out');
23+
}
24+
25+
@get('/test-table-not-found')
26+
testTableNotFound() {
27+
throw new TableNotFoundError('Table does not exist');
28+
}
29+
30+
@get('/test-connection-error')
31+
testConnectionError() {
32+
throw new DatabaseConnectionError('Connection failed');
33+
}
1434
}
1535

1636
beforeEach(() => {
@@ -24,26 +44,46 @@ describe('RejectProvider - DATABASE_ERROR_MAPPING_OPTIONS', () => {
2444
});
2545

2646
it('maps database error to HTTP 409 Conflict by default', async () => {
47+
app.bind(RestBindings.DATABASE_ERROR_MAPPING_OPTIONS).to({enabled: true});
48+
await app.start();
49+
client = createRestAppClient(app);
50+
51+
await client.get('/test-unique-error').expect(409);
52+
});
53+
54+
it('maps query timeout error to HTTP 504 Gateway Timeout', async () => {
55+
app.bind(RestBindings.DATABASE_ERROR_MAPPING_OPTIONS).to({enabled: true});
56+
await app.start();
57+
client = createRestAppClient(app);
58+
59+
const res = await client.get('/test-timeout-error').expect(504);
60+
expect(res.body.error.statusCode).to.equal(504);
61+
});
62+
63+
it('maps table not found error to HTTP 400 Bad Request', async () => {
64+
app.bind(RestBindings.DATABASE_ERROR_MAPPING_OPTIONS).to({enabled: true});
2765
await app.start();
2866
client = createRestAppClient(app);
2967

30-
await client.get('/test-db-error').expect(409);
68+
const res = await client.get('/test-table-not-found').expect(400);
69+
expect(res.body.error.statusCode).to.equal(400);
3170
});
3271

33-
it('maps database error to 409 Conflict when explicitly enabled', async () => {
72+
it('maps database connection error to HTTP 503 Service Unavailable', async () => {
3473
app.bind(RestBindings.DATABASE_ERROR_MAPPING_OPTIONS).to({enabled: true});
3574
await app.start();
3675
client = createRestAppClient(app);
3776

38-
await client.get('/test-db-error').expect(409);
77+
const res = await client.get('/test-connection-error').expect(503);
78+
expect(res.body.error.statusCode).to.equal(503);
3979
});
4080

4181
it('bypasses error mapping (returns 500) when disabled via app.bind()', async () => {
4282
app.bind(RestBindings.DATABASE_ERROR_MAPPING_OPTIONS).to({enabled: false});
4383
await app.start();
4484
client = createRestAppClient(app);
4585

46-
const res = await client.get('/test-db-error').expect(500);
86+
const res = await client.get('/test-unique-error').expect(500);
4787
expect(res.body.error.statusCode).to.equal(500);
4888
});
4989
});

‎packages/rest/src/__tests__/unit/error-writer/database-error-mapper.unit.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,18 @@ describe('mapDatabaseErrorToHttpError', () => {
4141
400,
4242
'The provided value violates a field constraint.',
4343
],
44+
[
45+
'TABLE_NOT_FOUND',
46+
HttpErrors.BadRequest,
47+
400,
48+
'The requested database table or relation does not exist.',
49+
],
50+
[
51+
'COLUMN_NOT_FOUND',
52+
HttpErrors.BadRequest,
53+
400,
54+
'The requested database column does not exist.',
55+
],
4456
[
4557
'DATA_TYPE_MISMATCH',
4658
HttpErrors.BadRequest,
@@ -53,6 +65,12 @@ describe('mapDatabaseErrorToHttpError', () => {
5365
400,
5466
'Attempted to modify a read-only or computed property.',
5567
],
68+
[
69+
'SYNTAX_ERROR',
70+
HttpErrors.BadRequest,
71+
400,
72+
'A database syntax or parse error occurred.',
73+
],
5674
[
5775
'QUERY_TIMEOUT',
5876
HttpErrors.GatewayTimeout,

‎packages/rest/src/error-writer/database-error-mapper.ts‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,11 @@ import {
66
CheckConstraintError,
77
DataTypeMismatchError,
88
DatabaseConnectionError,
9+
TableNotFoundError,
10+
ColumnNotFoundError,
11+
GeneratedColumnViolationError,
12+
QueryTimeoutError,
13+
DbSyntaxError,
914
} from '@loopback/repository';
1015
import {HttpErrors} from '../';
1116

@@ -72,19 +77,40 @@ export function mapDatabaseErrorToHttpError(
7277
);
7378
}
7479

80+
if (err instanceof TableNotFoundError || code === 'TABLE_NOT_FOUND') {
81+
return new HttpErrors.BadRequest(
82+
getMessage('The requested database table or relation does not exist.'),
83+
);
84+
}
85+
86+
if (err instanceof ColumnNotFoundError || code === 'COLUMN_NOT_FOUND') {
87+
return new HttpErrors.BadRequest(
88+
getMessage('The requested database column does not exist.'),
89+
);
90+
}
91+
92+
if (
93+
err instanceof GeneratedColumnViolationError ||
94+
code === 'GENERATED_COLUMN_VIOLATION'
95+
) {
96+
return new HttpErrors.BadRequest(
97+
getMessage('Attempted to modify a read-only or computed property.'),
98+
);
99+
}
100+
75101
if (err instanceof DataTypeMismatchError || code === 'DATA_TYPE_MISMATCH') {
76102
return new HttpErrors.BadRequest(
77103
getMessage('One or more properties contained invalid data types.'),
78104
);
79105
}
80106

81-
if (code === 'GENERATED_COLUMN_VIOLATION') {
107+
if (err instanceof DbSyntaxError || code === 'SYNTAX_ERROR') {
82108
return new HttpErrors.BadRequest(
83-
getMessage('Attempted to modify a read-only or computed property.'),
109+
getMessage('A database syntax or parse error occurred.'),
84110
);
85111
}
86112

87-
if (code === 'QUERY_TIMEOUT') {
113+
if (err instanceof QueryTimeoutError || code === 'QUERY_TIMEOUT') {
88114
return new HttpErrors.GatewayTimeout(
89115
getMessage('The database query execution timed out.'),
90116
);

0 commit comments

Comments
 (0)