Make 500 exception spit out JSON instead of HTML

Using Ajax, we sometimes have internal errors in the PHP code, making Yii spit out 500. This message is always in HTML, not JSON. Is it possible to make it JSON instead, for certain controller methods?

Something like this (but not manually):

header('Content-Type: application/json');
die(json_encode(['message' => 'Could not save label set.']));

Using the onException event for now.

1 Like cold be used to make your own handler.