Http异常

Notice: It is mainly for REST applications. Nest has error handling layer, which catches all unhandled exceptions. If - somewhere - in your application, you will throw an Exception, which is not HttpException (or inherited one), Nest will handle it and return to user below json object (500 status code):

注意:主要对REST应用程序适用。 Nest有错误处理层,该层可以捕获所有未被处理的异常。 当你的应用程序的某个地方抛出异常,如果该异常不是HttpException异常(或继承异常),Nest将会处理该异常并将该异常以下面的json对象(500 status code)形式返回给用户:

{
  "message": "Unkown exception"
}

异常结构

In your application, you should create your own Exceptions Hierarchy. All 'HTTP exceptions' should inherit from built-in HttpException. For example, you can create NotFoundException and UserNotFoundException classes:

你应该在你的应用程序中创建你自己的异常结构。所有的HTTP异常都应该继承自内置 的HttpException

import { HttpException } from '@nestjs/core';

export class NotFoundException extends HttpException {
    constructor(msg: string | object) {
        super(msg, 404);
    }
}

export class UserNotFoundException extends NotFoundException {
    constructor() {
        super('User not found.');
    }
}

Then - if you somewhere in your application throw UserNotFoundException, Nest will response to user with status code 404 and above json object:

接下类,如果你的应用程序的某个地方抛出UserNotFoundException,Nest将上示json对象以及404状态码返回给用户。

{
  "message": "User not found."
}

It allows you to focus on logic and make your code much easier to read.

它允许你重视逻辑,并使你的代码简单易懂。

results matching ""

    No results matching ""