我有多个任务函数调用validate(),如果存在验证错误,需要返回/转义main函数。是否可以使用typescript / javascript做这样的事情? (我在节点环境中工作)
public function sendMessageAction(Request $request)
{
$body = null;
$response = new Response();
$response->headers->set('Content-Type', 'application/json');
if (!$this->getUser()) {
$body = array('error' => 'user not found');
$response->setContent(json_encode($body));
return $response;
} else {
$body = array('success' => 'success');
}
$em = $this->getDoctrine()->getManager();
$recipient = $this->container->get('fos_user.user_manager');
$addressee = $recipient->findUserBy(array('id' => $request->get('addressee')));
$message = new Messages();
$message->setMessageText($request->get('messageText'));
$message->setAuthor($this->getUser());
$message->setAddressee($addressee);
$message->setReading(false);
$em->persist($message);
$em->flush();
$this->get('monolog.logger.message')->info('Message example: ' . $message->getReading());
$response->setContent(json_encode($body));
return $response;
}
我想避免在每个任务执行后创建一个 if 检查,以防我想用更多任务调用validate函数来扩展我的代码。我怎样才能完成这项任务?
答案 0 :(得分:1)
您可以返回一个布尔值并链接验证。
@Values({"one", "two", "three", "four"})
private String number;
答案 1 :(得分:0)
您可以使用简单的try / catch块,并在验证失败时让验证函数抛出错误。
const validate = () => {
if(validationSucceeds) {
return true;
} else {
throw 'error message';
}
}
const taskOne = () => {
validate() //some validation error happened when this got called..
}
const taskTwo = () => {
validate()
}
const mainFunction = () => {
try {
taskOne();
taskTwo(); //will not run because taskOne requested return
} catch(err) {
console.error(err);
return;
}
}
mainFunction();