[Boom, Hapi] Add default generic type to all error creation functions (#17048)

* [Boom] Add default generic type to all error creation functions

* [Boom] Change default generic Data type to any instead of null

* [Boom] Add tests for error creation without custom data

* [Boom, Hapi] Move tests for passing Boom errors to Hapi continuation functions into hapi package

* [boom] add wrap and unauthorized return BoomError with data as null
This commit is contained in:
Niklas Wulf
2017-06-08 15:33:24 +02:00
committed by Andy
parent 7cebbb3e51
commit 046b7d5ff9
4 changed files with 153 additions and 38 deletions

View File

@@ -0,0 +1,57 @@
import * as Hapi from 'hapi';
import * as Boom from 'boom';
// Assignment of a typical function to ContinuationValueFunction is possible
const handleError: Hapi.ContinuationValueFunction = (err?: Boom.BoomError | null, value?: any) => {
if (!err || !err.data.isCustom === true) {
return;
}
// assignment is possible due to default generic Data = any
const customError: Boom.BoomError<CustomData> = err;
// Discriminated union type works:
switch (customError.data.customType) {
case 'Custom1':
customError.data.custom1;
break;
case 'Custom2':
customError.data.custom2;
break;
}
};
// Accepts a simple Boom error
handleError(Boom.badData());
// Accepts an error with custom data
const errorWithData = Boom.badImplementation('', { custom1: 'test', customType: <'Custom1'>'Custom1', isCustom: <true>true });
handleError(errorWithData);
// Accepts an error with a more explicit type
const errorWithExplicitType: Boom.BoomError<CustomData> = errorWithData;
handleError(errorWithExplicitType);
// Accepts an error with an even more explicit type
const errorWithConcreteCustomData: Boom.BoomError<CustomData1> = errorWithData; // assignment to CustomData2 would not be possible
handleError(errorWithConcreteCustomData);
/**
* Some complex error data types:
*/
interface CustomDataBase {
isCustom: true;
}
interface CustomData1 extends CustomDataBase {
customType: 'Custom1';
custom1: string;
}
interface CustomData2 extends CustomDataBase {
customType: 'Custom2';
custom2: string;
}
type CustomData = CustomData1 | CustomData2;

View File

@@ -18,6 +18,7 @@
"files": [
"index.d.ts",
"test/connection/table.ts",
"test/continuation/errors.ts",
"test/getting-started/01-creating-a-server.ts",
"test/getting-started/02-adding-routes.ts",
"test/getting-started/03-serving-static-content.ts",