50 lines
1.8 KiB
Python
50 lines
1.8 KiB
Python
from marshmallow import ValidationError
|
|
|
|
from common.exceptions.app_exception import AppException
|
|
from common.response.api_response import error_response
|
|
from common.constants.status_code import (
|
|
HTTP_BAD_REQUEST,
|
|
HTTP_NOT_FOUND,
|
|
HTTP_INTERNAL_SERVER_ERROR
|
|
)
|
|
# Phải tạo global error handler(ở project cũ là để phần này ra app.py nhưng bây giờ chỉ cần tạo file hander rồi đăng kí ở app.py để nó thành global bắt lỗi toàn dự án)
|
|
# Ngoài ra để có được các lỗi của toàn dự án, thì phải custom exception theo dự án bằng cách kế thừa lại Exception để custom thêm thuộc tính mới
|
|
|
|
def register_error_handlers(app): # Đăng ký hàm này ở app.py để nó bắt lỗi toàn dự án
|
|
|
|
@app.errorhandler(AppException)
|
|
def handle_app_exception(error):
|
|
return error_response(
|
|
message=error.message,
|
|
error=error.error_code,
|
|
status_code=error.status_code,
|
|
details=getattr(error, "payload", None)
|
|
)
|
|
|
|
|
|
@app.errorhandler(ValidationError)
|
|
def handle_validation_error(error):
|
|
return error_response(
|
|
message="Invalid request data",
|
|
error="VALIDATION_ERROR",
|
|
status_code=HTTP_BAD_REQUEST,
|
|
details=error.messages
|
|
)
|
|
|
|
|
|
@app.errorhandler(404)
|
|
def handle_not_found(error):
|
|
return error_response(
|
|
message="Route not found",
|
|
error="NOT_FOUND",
|
|
status_code=HTTP_NOT_FOUND
|
|
)
|
|
|
|
|
|
@app.errorhandler(500)
|
|
def handle_internal_error(error):
|
|
return error_response(
|
|
message="Internal server error",
|
|
error="INTERNAL_SERVER_ERROR",
|
|
status_code=HTTP_INTERNAL_SERVER_ERROR
|
|
) |