简体   繁体   中英

FosRestbundle force content-type for error messages

I'm looking for a simple, stupid solution to force the content-type to application/json for all http error messages in (like MethodNotAllowedHttpException etc.).

Example request headers:

Content-Type: application/x-www-form-urlencoded 
Accept: */*

Current response headers ( MethodNotAllowedHttpException ):

Content-Type: text/html; charset=UTF-8 

you can throw the error if the value in the header fails your logic test. then in your catch statement, return a json response. something like this (untested code)

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

// .....

public function myAction(Request $request){

    try{
        // ...
        $cType = $request->headers->get('Content-Type');
        // logic for testing if the content type is allowed
        if(!in_array($cType,$allowedArray)){
            throw new MethodNotAllowedHttpException();
        }
        // .....

    }catch(\Exception $e){
        if(get_class($e) == "MethodNotAllowedHttpException"){
            $data = array("success"=>false,"message"=>"Method not allowed")
            return new JsonResponse($data);
        }
    }
}

This way you can handle different exceptions in different ways. I'm not sure if it was the content type that you want to use to determine if you throw the exception or not, but you can get any header info by using $request->headers->get()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM