try { // Some code that may throw an exception } catch (Exception $e) { $statusCode = $e->getStatusCode(); // Handle the error and return the appropriate HTTP status code }
class CustomException extends Exception { public function __construct($message = "", $code = 400, Throwable $previous = null) { parent::__construct($message, $code, $previous); } } try { // Some code that may throw a custom exception } catch (CustomException $e) { $statusCode = $e->getStatusCode(); // Handle the error and return the appropriate HTTP status code }In the first example, we catch a generic Exception and retrieve the status code using the getStatusCode() method. In the second example, we define a custom exception class that sets a default status code of 400 and retrieve the status code in the catch block. Package/Library: The Exception class is part of the PHP core library and is included by default in all PHP installations.