Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

python - raise exception as http response

I'm using django and vue to write a Programmer. Could I raise an exception as a http response, so I can raise the exception anywhere, and do not need to catch it in the django view function, and then reassemble it into a new http response.

Pseudocode

try:
  a = ['0']
  b = a[2]
except IndexError as e:
  raise ExceptionAsHttpResponse(status=404, reason='haha')  # Not implemented, hope to get your help.

after the raise ExceptionAsHttpResponse, the frontend can just accquire the status and reason

question from:https://stackoverflow.com/questions/66057452/raise-exception-as-http-response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes you can, you can simply use Http404. For example:

from django.http import Http404

try:
  a = ['0']
  b = a[2]
except IndexError as e:
  raise Http404('your reason')

But that is in general should not be practiced, because http response should be generated from view. If you have helper functions or service methods, then it is better to raise a generic error(ie IndexError) from there and catch them in view, then render a error response.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...