我正在使用Typescript,Koa和Sequelize构建简单的REST API。
如果客户端使用空字段“ title”或“ author”执行无效的PUT请求,则会返回500错误。我宁愿不报告这样的错误,而是要返回“ 400 Bad Request”。 正确的方法是什么?
这是控制器的一部分:
import {JsonController, Get, Post, Put, Body, Param} from "routing-controllers";
import {Book} from "../models/Book";
@JsonController("/api")
export class BookController {
@Put("/books/:id")
async update(@Param("id") id: number, @Body() book: Book) {
return await Book.update(book, {where: {id: id}});
}
}
这是我使用Sequelize验证器作为装饰器的模型:
import {Table, Column, NotEmpty, Equals, Model, HasMany} from 'sequelize-typescript';
@Table({tableName: 'Books'})
export class Book extends Model<Book> {
@NotEmpty
@Column
title: string;
@NotEmpty
@Column
author: string;
}
错误消息:
"message": "Validation error: Validation notEmpty on title failed,\nValidation error: Validation notEmpty on author failed"
答案 0 :(得分:0)
尝试使用 ValidationFailed 钩子
import {ValidationFailed} from 'sequelize-typescript'
@ValidationFailed
static afterValidateHook(instance, options, error) {
throw new ErrorWithStatus(error.message, 400);
}
ErrorWithStatus 在哪里
class ErrorWithStatus extends Error {
status: number;
constructor(message, status = 400) {
super(message);
this.status = status;
}
}