Yii2 show error when exception occurs - exception

I have this code in my controller:
...
if (Model::validateMultiple($ttepk)) {
$transaction = \Yii::$app->db->beginTransaction();
try {
foreach ($ttepk as $ttep) {
$ttep->save(false);
if (!$ttep->assignPs()) {
throw new UserException('assignPs failed');
}
}
$transaction->commit();
return $this->redirect(['index']);
} catch (Exception $ex) {
$transaction->rollBack();
throw $ex;
}
}
...
in model:
...
public function assignPs() {
foreach (...) {
$ttepetk[...] = new Ttepet;
$ttepetk[...]->ttepId = $this->id;
... // set other attributes
}
}
if (Model::validateMultiple($ttepetk)) {
foreach ($ttepetk as $ttepet) {
$ttepet->save(false);
}
return true;
} else {
return false;
}
}
...
Everything is working fine (no inserts are happening if any of the models fail validation), except that I would like to see the exact error, exactly by which Ttep (each Ttep is a model) and by which Ttepet (Ttep:Ttepet = 1:N) has the error happened, and what was that. Now I see the Exeption page only, and I don't know how to make the errors visible. Please point me to the right direction. Thanks!

You could iterate on each single model validating one by one and getting the errors when occurs ...
if (Model::validateMultiple($ttepetk)) {
foreach ($ttepetk as $ttepet) {
$ttepet->save(false);
}
return true;
} else {
foreach($ttepetk as $model){
if ($model->validate()) {
// all inputs are valid
} else {
// validation failed: $errors is an array containing error messages
$errors = $model->errors;
}
}
return $errors;
}
you can get the errors this way
$myErrorResult = $ttep->assignPs();
if (!$myErrorResult) {
......

Related

Laravel 8 Handler Undefined class 'Exception'

I work in API Laravel project and try to handler
"message": "No query results for model ID"
and page 404
I use this function but don't send anything in API and no effect on 404 pages
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class Handler extends ExceptionHandler
{
public function render($request, Exception $e)
{
// "message": "No query results for model ID" in API
if ($e instanceof ModelNotFoundException) {
return response()->json(['error' => 'Data not found.']);
}
if($this->isHttpException($e))
{
switch ($e->getStatusCode())
{
// not found
case 404:
return redirect()->guest('home');
break;
// internal error
case '500':
return redirect()->guest('home');
break;
default:
return $this->renderHttpException($e);
break;
}
}
else
{
return parent::render($request, $e);
}
}
}
Use Throwable not Exception
public function render($request, Throwable $e)
{
// "message": "No query results for model ID" in API
if ($e instanceof ModelNotFoundException) {
return response()->json(['error' => 'Data not found.']);
}
return parent::render($request, $e);
}

How to change the behavior of the beforeAction?

There is a beforeAction() in Controller.php
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
}
return true;
}
return false;
}
It throws an exception but I want to change this in my own controller which extends controller.php. I try something like that
public function beforeAction($action) {
if ($this->enableCsrfValidation && Yii::$app->getErrorHandler()->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
Yii::$app->session->setFlash('info', 'Error');
$this->goBack();
}
return parent::beforeAction($action);
}
But it still shows exception.
Not sure but it might work with just changing this row...
$this->goBack();
into...
return $this->goBack();
Another approach would be to catch the Exception from the parent instead. Later there might be other events triggered by beforeAction and if not calling the parent::beforeAction these may not be run as intended.

while using JsonRequestBehavior in web api giving error saying cannot convert to json.serializer

I am getting the following compilation error:
cannot convert from 'System.Web.Mvc.JsonRequestBehavior' to 'Newtonsoft.Json.JsonSerializerSettings'
code
public class PondController : ApiController
{
public JsonResult Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
return Json(new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception Ex)
{
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
}
You are trying to use code snippet from ASP.NET MVC in ASP.NET WebAPI controller. In WebAPI the results and methods have different signatures. Try following:
public JsonResult<object> Get()
{
try
{
using (smartpondEntities DB = new smartpondEntities())
{
var pond = DB.Temperatures.OrderByDescending(x => x.WaterTemperature).FirstOrDefault();
return Json((object)new { success = true, sensorsdata = new { id = pond.WaterTemperature, CurrentTime = pond.CreatedDate } });
}
}
catch (Exception Ex)
{
}
return Json((object)new { success = false });
}

how do i return json object in action result in mvc

I have a method of action result in a controller where i have some conditions if the conditions fails then i want to send a json object to the view but i am not able to do it. can any one help me out.
[HttpPost]
public ActionResult Loginuser(LoginDetails newlogin)
{
LoginDetails objlogin = new LoginDetails();
objlogin.UserEmail = newlogin.UserEmail;
objlogin.UserPassword = newlogin.UserPassword;
try
{
if (ModelState.IsValid)
{
RegisterBAL Regball = new RegisterBAL();
objlogin = Regball.LoginUserBAL(objlogin);
if(objlogin.ResponseCode == "000")
{
if(objlogin.UserRole =="CityHelpdesk")
{
return RedirectToAction("CityHelpdesk", "RoleDashbord");
}
if (objlogin.UserRole == "CityAdmin")
{
return RedirectToAction("CityAdmin", "RoleDashbord");
}
if (objlogin.UserRole == "StateAdmin")
{
return RedirectToAction("StateAdmin", "RoleDashbord");
}
if (objlogin.UserRole == "StateHelpdesk")
{
return RedirectToAction("StateHelpdesk", "RoleDashbord");
}
}
else
{
return json object//// Hear i want to return the json object
}
}
}
catch (Exception)
{
objlogin.ResponseCode = "EXC";
}
}
You can return Json via the return Json() method
For your situation, that would be return Json(objlogin);
Be aware that you will be posting the username and password back to the client. Better filter out the fields that you need and return a new model
You can Use:
return NotFound({JsonObject})
Or
return BadRequest({JsonObject})
Or
return Ok({JsonObject})
Or
return Content("String")

CHECKPOINT-FAIL com.thoughtworks.selenium.SeleniumException: this.waitForCondition is not a function

A simple function defined in the user-extensions.js :
Selenium.prototype.doGetThis = function(){
var errors = "";
if (browserVersion.isChrome) {
errors = true;
} else {
throw new SeleniumError("TODO: Non-FF browser...");
}
return errors;
}
The Selenium.java file:
String getThis() {
return this.commandProcessor.doCommand("getThis", EMPTY_STRING_ARRAY);
}
Running the test throws a SeleniumException:
CHECKPOINT-FAIL com.thoughtworks.selenium.SeleniumException: this.waitForCondition is not a function
Could this exception be avoided?
Settings:
selenium server 2.0a5
firefox 3.6.11
After I added the ; I still got the same exception.
Selenium.prototype.doGetThis = function(){
var errors = "";
if (browserVersion.isChrome) {
errors = true;
} else {
throw new SeleniumError("TODO: Non-FF browser...");
}
return errors;
};
It seems that you need to add a ; to the end of your doGetThis function:
Selenium.prototype.doGetThis = function(){
var errors = "";
if (browserVersion.isChrome) {
errors = true;
} else {
throw new SeleniumError("TODO: Non-FF browser...");
}
return errors;
};