假設我有一個自定義的Wordpress REST API路由,并且我在回呼中拋出了一個未處理的例外:
register_rest_route( $namespace, "/test", [
"methods" => "get",
"permission_callback" => "__return_true"。
"callback" => function($req ) {
throw new Exception( "錯誤!!" ) 。
}
]);
如果我查詢這個路由,Wordpress會回傳一個顯示錯誤資訊的HTML頁面,這對主題或管理區來說沒有問題,但對REST API來說,我寧愿回傳一個WP_Error。
我想我可以在回呼代碼周圍放一個try/catch塊,就像這樣:
register_rest_route( $namespace, "/test", [
"methods" => "get",
"permission_callback" => "__return_true"。
"callback" => function($req ) {
try{
throw new Exception( "錯誤!!" ) 。
} catch( Throwable $e ) {
return new WP_Error( "rest_error", $e->get_error_message() ) 。
}
}
]);
但是,我必須對我的所有自定義路由進行這樣的處理,對嗎?
我是否有辦法為任何自定義端點中拋出的未捕獲的例外設定一個 "全域 "默認回應?
uj5u.com熱心網友回復:
我已經找到了一種方法,用set_exception_handler來做。不確定這是否是最好的方法,但它似乎是有效的:
set_exception_handler( array( $this, "handle_uncaught_exceptions" /span> ) );
public function handle_uncaught_exceptions handle_uncaught_exceptions( Throwable $e) {
//span>首先,記錄例外。
log_from_exception( "errors"/span>, "alert"/span>, $e ) 。
//現在我們必須回傳一個回應。默認情況下,當一個未捕獲的例外被拋出時(致命錯誤),Wordpress回傳。
//一個帶有錯誤資訊的HTML頁面。這很好,例如對于主題或管理區,但對于REST請求,我們寧愿
///回傳一個看起來像WP_REST_Response的回應。
if( is_rest_request() ) {
//設定回應代碼為500。
http_response_code(500)。
///設定跨域頭資訊
header( "Access-Control-Allow-Origin: " . $_ENV["FRONTEND_URL"] 。
header( "Access-Control-Allow-Credentials: true" ) 。
//發送回應。
$response = [
"code" => "rest_fatal_error"。
"message" => "發生了一個致命的錯誤".
];
wp_send_json( $response ) 。
} else {
//對于非REST請求,我們希望重置默認行為,即發送一個帶有錯誤資訊的HTML頁面。
wp_die( $e->getMessage() )。
}
is_rest_request是一個自定義函式:
function is_rest_request() /span>{
$uri = $_SERVER["REQUEST_URI"/span>]。
if ( empty( $uri ) ) {
return false;
}
$restPrefix = trailingslashit( rest_get_url_prefix() ) ; //resolves to "wp-json/"
$isRestApiRequest = strpos( $uri, $restPrefix ) ? !== false;
return $isRestApiRequest;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/309949.html
標籤:
上一篇:如何在我的服務中取值請求DTOs@PutMapping
下一篇:HATEOAS鏈接最佳實踐
