Giter Site home page Giter Site logo

Comments (11)

jamesmacwhite avatar jamesmacwhite commented on August 23, 2024 1

@brandonkelly Ah that's what I'm missing my pattern is off since the changes. asJson() is fine with passing an error key to replicate the same behaviour that asErrorJson() would do. Thanks for taking the time to explain and sticking with me!

from cms.

brandonkelly avatar brandonkelly commented on August 23, 2024

A response is definitely returned by asFailure(); it’s just marked with a 400 status code. So you will need to update your client-side logic to handle non-2xx responses.

Alternatively, if you don’t want to change the response behavior, you can start calling asJson() and pass in the error key yourself (which is all that asErrorJson() was doing):

return $this->asJson([
    'error' => 'No param was provided for the request.',
]);

from cms.

jamesmacwhite avatar jamesmacwhite commented on August 23, 2024

@brandonkelly Thanks for the info. The main area I was highlighting was when making a HTTP request to the controller when it was hitting the condition to essentially return a response, with asErrorJson() it was returning the error, with asFailure() it just threw a 404 error, didn't return the message set. I'm aware, that the asFailure() doesn't return the error key, but the 404 response seemed odd.

from cms.

brandonkelly avatar brandonkelly commented on August 23, 2024

@jamesmacwhite Did you delete the return statement in the process by chance? You still need to be returning the response:

if (!$param) {
    return $this->asFailure(...);
}

from cms.

jamesmacwhite avatar jamesmacwhite commented on August 23, 2024

@brandonkelly Nope, I was still returning the result. It is odd. I must be missing something obvious, but if I replace asErrorJson() with asFailure() it just doesn't return a 400 response it seems.

from cms.

brandonkelly avatar brandonkelly commented on August 23, 2024

Are you 100% sure that that line of code is actually getting executed? Maybe try throwing an exception there instead, and verify that a 500 response comes back.

from cms.

jamesmacwhite avatar jamesmacwhite commented on August 23, 2024

100% sure, here's the controller example:

public function actionMyAction(): ?Response
{
  $param = $this->request->getQueryParam('param');
  if (!param) {
      return $this->asFailure('Missing parameter.');
  }
}

I've done a dd() in the condition where the return statement and confirmed it is being hit. However if I use asFailure() the response ends up being null and 200 OK.

Compared to asErrorJson() which returns the message, but noticed it's not actually a 400 in checking developer tools console, it's a 200 still...

public function actionMyAction(): ?Response
{
  $param = $this->request->getQueryParam('param');
  if (!param) {
      return $this->asErrorJson('Missing parameter.');
  }
}

There's something funky going on with my Craft setup I think...

I could throw a 400 error exception, but I think I'm missing something fundamental, considering the code works on Craft CMS 3.

Ah just noticed the status being 200 is expected per: #3890, but the mystery remains on the asFailure() message not being returned.

from cms.

brandonkelly avatar brandonkelly commented on August 23, 2024

Compared to asErrorJson() which returns the message, but noticed it's not actually a 400 in checking developer tools console, it's a 200 still...

That’s expected; asErrorJson() has always returned a 200 response, which is part of the reason we’ve deprecated it and stopped using it in favor of asFailure().

What happens if you do this:

return $this->asErrorJson('Missing parameter.')->setStatusCode(400);

from cms.

jamesmacwhite avatar jamesmacwhite commented on August 23, 2024

That works and throws a 400. I know there's also a hack you can use an event to make it a 400, but changing setStatusCode() is fine.

A bit more debugging, dumping:

dd($this->asErrorJson('Missing Parameter')) returns:

craft\web\Response {#226 ▼
  -_events: []
  -_eventWildcards: []
  -_behaviors: null
  +exitStatus: 0
  +format: "json"
  +acceptMimeType: null
  +acceptParams: []
  +formatters: array:5 [▶]
  +data: array:1 [▶]
  +content: null
  +stream: null
  +charset: "UTF-8"
  +statusText: "OK"
  +version: "1.1"
  +isSent: false
  -_statusCode: 200
  -_headers: yii\web\HeaderCollection {#225 ▶}
  -_cookies: null
  +defaultFormatters: []
  -_isPrepared: false
}

dd($this->asFailure('Missing parameter')) returns

null

This is in a controller for a site request. I'm wondering if that has anything to do with the behaviour being different?

from cms.

brandonkelly avatar brandonkelly commented on August 23, 2024

OK, so the issue is that there’s no Accept: application/json header, which is required for asFailure() to return a JSON response.

When you say this is a site request, do you mean you’re accessing the controller action directly from the main browser window? If so, and you are expecting to get a JSON response, and just have that be output in the browser window, you’ll need to call return $this->asJson() yourself, and pass an array with an error key as suggested earlier. You can optionally chain on ->setStatusCode(400) if you want a 400 response code, too.

return $this->asJson([
    'error' => 'No param was provided for the request.',
])->setStatusCode(400);

Or, if this is an Ajax request, then you just need to start sending an Accept: application/json header.

const response = await fetch(url, {
  headers: {
    accept: 'application/json',
  },
  // ...
});

from cms.

brandonkelly avatar brandonkelly commented on August 23, 2024

Glad that helped! Sorry, I should have thought about that difference between asFailure() and asJson()/asErrorJson() earlier 🤦‍♂️

from cms.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.