Old question, but I hope this helps someone in the future. The accepted answer doesn't really answer the original question...
You can do this with django rest framework easily by raising ApiException:
from rest_framework.exceptions import APIException
try:
...
except ...:
raise APIException('custom exception message')
This will return a response with status 500 from your view. Pretty useful if you are calling another function from your API and you don't want to manage return values from this function to decide if returning a response with status 500.
You can use it like this:
raise ApiException
And the default response message (at the time of writing this) will be 'A server error occurred.'.
There's a few predefined ApiException subclasses to raise different kinds of errors, check the file rest_framework.exceptions, if you need one that is not in there, you can extend ApiException like this:
from rest_framework.exceptions import APIException
class YourCustomApiExceptionName(APIException):
def __init__(self, status, detail):
self.status_code = status
self.detail = detail
Usage:
raise YourCustomApiExceptionName(100, 'continue')
You can also define custom status and detail but wouldn't make much sense in most cases.
EDIT:
If for some reason you are working without DRF, you can just copy the APIException code instead of installing the DRF package:
[To see links please register here]