目标:一个 REST API,如何写异常,让client端使用的舒舒服服。
先来个热身
一、异常处理
Ref: Flask Rest API -Part:4- Exception Handling
需要单独写一个这样的文件:errors.py
#~/movie-bag/resources/errors.py class InternalServerError(Exception): pass class SchemaValidationError(Exception): pass class MovieAlreadyExistsError(Exception): pass class UpdatingMovieError(Exception): pass class DeletingMovieError(Exception): pass class MovieNotExistsError(Exception): pass class EmailAlreadyExistsError(Exception): pass class UnauthorizedError(Exception): pass errors = { "InternalServerError": { "message": "Something went wrong", "status": 500 }, "SchemaValidationError": { "message": "Request is missing required fields", "status": 400 }, "MovieAlreadyExistsError": { "message": "Movie with given name already exists", "status": 400 }, "UpdatingMovieError": { "message": "Updating movie added by other is forbidden", "status": 403 }, "DeletingMovieError": { "message": "Deleting movie added by other is forbidden", "status": 403 }, "MovieNotExistsError": { "message": "Movie with given id doesn't exists", "status": 400 }, "EmailAlreadyExistsError": { "message": "User with given email address already exists", "status": 400 }, "UnauthorizedError": { "message": "Invalid username or password", "status": 401 } }