Exception handling
Midway provides a built-in exception handler that handles all unhandled exceptions in the application. When your application code throws an exception handler, the handler catches the exception and waits for the user to handle it.
The execution position of the exception handler is behind the middleware, so it can intercept all errors thrown by the middleware and business.
Http exception
In Http requests, Midway provides a common MidwayHttpError
type of exception, which inherits from standard MidwayError
.
export class MidwayHttpError extends MidwayError {
// ...
}
We can throw this error during the request. Since the error contains a status code, the Http program will automatically return the status code.
For example, the following code throws an error containing the 400 status code.
import { MidwayHttpError } from '@midwayjs/core';
// ...
async findAll() {
throw new MidwayHttpError('my custom error', HttpStatus.BAD_REQUEST);
}
// got status: 400
However, we seldom do this in general. Most business errors are reused and error messages are basically fixed. In order to reduce duplicate definitions, we can customize some exception types.
For example, to customize an Http exception with a status code of 400, you can define an error as follows.
// src/error/custom.error.ts
import { HttpStatus } from '@midwayjs/core';
export class CustomHttpError extends MidwayHttpError {
constructor() {
super('my custom error', HttpStatus.BAD_REQUEST);
}
}
Then throw the use in the business.
import { CustomHttpError } from './error/custom.error';
// ...
async findAll() {
throw new CustomHttpError();
}