使用所需格式的路由控制器引发自定义消息错误



我有一个使用路由控制器的Node APP,Readme中有一个名为Throw HTTP errors的部分,示例不言自明。

但问题是当我试图重现这些线条时。在我的代码中,我有这样的例子(出于测试目的,我想不做任何事情就抛出异常(:

@Post('/')
async post(): Promise<any> {
throw new NotFoundError(`User was not found.`);
}

其中NotFoundError是从routing-controllers导入的。这应该有效,但是。。。它返回整个错误跟踪,而不是像这样的对象

{
"name": "NotFoundError",
"message": "User was not found."
}

状态为404,但返回的文本为:

Error
at new HttpError (/path_to_the_code/node_modules/src/http-error/HttpError.ts:16:18)
at new NotFoundError (/path_to_the_code/node_modules/src/http-error/NotFoundError.ts:10:5)
at HelloWorld.<anonymous> (/path_to_the_code/src/controller/controllers/HelloWorldController.ts:20:15)
at Generator.next (<anonymous>)
at /path_to_the_code/src/controller/controllers/HelloWorldController.ts:17:71
at new Promise (<anonymous>)
at __awaiter (/path_to_the_code/src/controller/controllers/HelloWorldController.ts:13:12)
at HelloWorld.post (/path_to_the_code/src/controller/controllers/HelloWorldController.ts:36:16)
at ActionMetadata.callMethod (/path_to_the_code/node_modules/src/metadata/ActionMetadata.ts:252:44)
at /path_to_the_code/node_modules/src/RoutingControllers.ts:123:28

我正在尝试调试,线路13:12是另一条路线:

@Get('/')
async get(): Promise<any> {
return this.helloWorldService.getHello()
}

顺便说一下,整个控制器是这样的:

import { Controller, Get, NotFoundError, Post } from 'routing-controllers';
import { Service } from 'typedi';
import { HelloWorldService } from '../../business/services/HelloWorldService';
@Service()
@Controller('/hello-world')
export class HelloWorld {
constructor(public helloWorldService: HelloWorldService) { }
@Get('/')
async get(): Promise<any> {
return this.helloWorldService.getHello()
}
@Post('/')
async post(): Promise<any> {
throw new NotFoundError(`User was not found.`);
}
}

所以我不想知道错误是从哪里来的。。。

我想要的是从服务器接收文档中显示的相同结构:{name:'', message:''},而不是整个堆栈跟踪。

顺便说一下,这似乎是一个内部错误,即使HTTP代码也能正常工作。

提前谢谢。

我对使用Express和路由控制器很陌生,所以我不确定这是否是最好的方法。我通过添加一个自定义错误处理程序作为中间件来实现它:

import { Middleware, ExpressErrorMiddlewareInterface, HttpError } from 'routing-controllers';
@Middleware({ type: 'after' })
export class HttpErrorHandler implements ExpressErrorMiddlewareInterface {
error(error: any, request: any, response: any, next: (err: any) => any) {
if (error instanceof HttpError) {
response.status(error.httpCode).json(error);
}
next(error);
}
}

请注意,我使用error.httpCode设置状态,然后将error转换为JSON。之后,我将错误处理程序添加到middlewares数组中,并将defaultErrorHandler设置为false:

const app = createExpressServer({
defaultErrorHandler: false,
middlewares: [
HttpErrorHandler
],
// ...
});

我现在得到这样的响应(以及响应上的适当状态代码(:

{
httpCode: 404,
name: "NotFoundError",
message: "User was not found",
}

最新更新