从Listener中抛出异常

时间:2018-05-07 13:17:35

标签: android asynchronous exception exception-handling listener

我正在为执行相同工作的异步操作替换同步方法。如果出现问题,旧方法会抛出自定义异常。现在我在新方法中有一个监听器,我不知道如何继续抛出异常:

<?php

namespace App\Http\Controllers;

use App\Upload;
use Illuminate\Http\Request;

class UploadController extends Controller
{
    public function upload(Request $request)
    {
        $originalName = $request->file('file')->getClientOriginalName();
        $fileSize = $request->file('file')->getClientSize();
        $path = $request->file('file')->store('documents');
        $explode = explode('documents/', $path);
        $name = $explode[1];
        $uniqueId = $this->generateUniqueId();

        $upload = new Upload();
        $upload->unique_id = $uniqueId;
        $upload->name = $name;
        $upload->path = $path;
        $upload->original_name = $originalName;
        $upload->size = $fileSize;

        if ($upload->save())
        {
            return response()->json([
                'original_name' => $originalName,
                'size' => $fileSize,
                'url' => env('AWS_URL') . $path,
                'id' => $uniqueId,
                'status' => 'OK'
            ]);
        }

        return response()->json(['status' => 'BAD', 'message' => 'There was a problem saving your file.']);
    }

    public function generateUniqueId()
    {
        $result = '1';
        $result .= rand(100000000, 999999999);

        while(Upload::where('unique_id', '=', $result)->first())
        {
            $result = '1';
            $result .= rand(100000000, 999999999);
        }

        return $result;
    }
}

此异常稍后被另一个类中的另一个方法捕获,该方法根据异常消息向用户提供反馈。

2 个答案:

答案 0 :(得分:0)

这可能听起来很傻,但只是扔掉它:p

https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html

@Override
protected void methodBeingChanged() throws customException {

    asyncMethod(new Handler() {
        @Override
        public void onSuccess(String response, int responseCode) {
        }

        @Override
        public void onError() {
            try {
                throw new customException ();
            }catch(customException cEx) {
                // Do stuff
            }
        }
    });

}

答案 1 :(得分:0)

这是不可能的。您的异步任务在另一个线程上运行,您当前的methodBeingChanged立即完成,这意味着methodBeingChanged永远不会抛出异常。

唯一的解决方案是修改调用者代码,为特定异常添加另一个侦听器方法