Comments (11)
@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.
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.
@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.
@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.
@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.
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.
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.
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.
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.
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.
Glad that helped! Sorry, I should have thought about that difference between asFailure()
and asJson()
/asErrorJson()
earlier 🤦♂️
from cms.
Related Issues (20)
- [4.x][5.x]: Unable to expand/collapse entry/category in field element select modal if descendant already selected for field HOT 2
- [4.x]: Date Field isn't filtering >= now correctly HOT 1
- [5.x]: GraphQL - Setting unknown property: craft\elements\db\EntryQuery::volumeId HOT 1
- [5.x]: Adding Two-Step Verification with a Permissions-Policy that does not allow synchronous requests HOT 3
- [5.x]: Two-step verification set-up key has extra whitespace at the end when copied HOT 2
- [5.x] / [4.x]: CP Slow with two or more users logged in HOT 5
- [5.x]: Modified matrix entries don't get updated after adding or deleting an entry to the matrix (Copy of #15069) HOT 2
- [5.x]: Error in CraftCMS: prepareForJsonColumn() Argument Type Mismatch in FindAndReplace.php HOT 1
- [4.x]: Migration throws error relating to UserGroupEvent when removing a user group HOT 5
- [4.x]: Links in release note alerts not rendered HOT 1
- [5.x]: Migration `m230511_215903_content_refactor` fails HOT 3
- Revisions for singles - Remove other sites from the author view (multisite) HOT 6
- [4.x]: error: Undefined array key "label" HOT 1
- Response Headers Ignoring Header Tags [4.x]: HOT 6
- [5.x]: Pagination info on overview page not updating after bulk editing with filter applied HOT 2
- [5.x]: Setting field values in Entry::EVENT_BEFORE_SAVE doesn't work when $firstSave is true
- [5.x]: Custom field conditions in element queries are case-sensitive now HOT 1
- [5.x]: Variant Overview has table fields that doesn't exist on the variant layout HOT 3
- [5.x]: Incorrect CP console request URLs HOT 3
- [5.x]: Matrix blocks can't be reordered HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from cms.