Reputation: 13109
I created a global express request error handler in TypeScript (3.8.3)
import express from 'express'
import { ProblemDocument } from 'http-problem-details'
const registerExpressProblemJsonResponse = (): void => {
express.response.httpProblemJSON = function(problemDocument): void { // line 5
this.set('Content-Type', 'application/problem+json')
this.status(problemDocument.status)
this.send(problemDocument)
}
}
export { registerExpressProblemJsonResponse }
import { NextFunction, Request, Response } from 'express'
const GlobalRequestErrorHandler = (logger: any) => {
return (
err: Error,
req: Request,
res: Response,
next: NextFunction
): void => {
logger.error(`${req.method} ${req.url} Error: ${err}`, { error: err })
if (!res.headersSent) {
return res.httpProblemJSON( // line 25
new ProblemDocument({ status: 500, type: 'https://tempuri.org/error' })
)
} else {
logger.warn(
`[global-request-error-handler] ${req.method} ${req.url} has an error path returning a response already`
)
}
}
}
export { GlobalRequestErrorHandler }
I've extended the express request object (src/types/types.d.ts
):
import { ProblemDocument } from 'http-problem-details'
declare namespace Express {
export interface Response {
httpProblemJSON(problemDocument: ProblemDocument): void
}
}
This is my tsconfig.json
:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"declaration": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"baseUrl": ".",
"paths": {
"*": ["node_modules/*", "src/types/*"]
}
},
"include": ["src/**/*"]
}
I've installed "@types/express": "^4.17.3"
and "express": "^4.17.1"
.
When running tsc
, I get these errors:
src/index.ts:5:20 - error TS2339: Property 'httpProblemJSON' does not exist on type 'Response<any>'.
5 express.response.httpProblemJSON = function(
~~~~~~~~~~~~~~~
src/index.ts:25:18 - error TS2339: Property 'httpProblemJSON' does not exist on type 'Response<any>'.
25 return res.httpProblemJSON(
~~~~~~~~~~~~~~~
Found 2 errors.
What am I doing wrong here?
Upvotes: 0
Views: 190
Reputation: 13654
Your declaration for Express is wrong.
It supposes to look like this:
declare global {
namespace Express {
interface Response {
httpProblemJSON(problemDocument: ProblemDocument): void
}
}
}
Upvotes: 1