java - 删除重复的 try/catch 代码

标签 java web-services methods try-catch

我在许多方法中都有以下代码

try{ user = userList.get(user_id); }
catch(Exception e) { return "USER_NOT_FOUND"; }

我发现自己在不同的方法中使用了很多代码,为了消除重复,我可以尝试创建这样的方法:(示例)

.. returnUser(){

    try{ return user = userList.get(user_id); }
    catch(Exception e) { return "USER_NOT_FOUND"; }
}

但是,如果未找到用户,这只会返回用户或字符串,并且不会退出该方法:(不工作)

public static void main(String[] args){
    System.out.pring("This will run always");
    User a = returnUser();
    System.out.pring("this should only run if a user was returned");
    System.out.pring("otherwise 'USER_NOT_FOUND' should be returned and end app.");
    ....
    ....
    return "Succsess";
 }

有更好的方法吗?您可以只从方法中返回一个制动器并返回字符串并结束该方法吗?

代码示例:

public String completeTodo(){

    Todo todo; // Instantiate User object
    User user; // Instantiate todo object

    try{ todo = todoList.get(user_id); } //repeditive in all functions
    catch(Exception e) { return "TODO_NOT_FOUND"; }

    try{ user = userList.get(user_id); } //repeditive in some functions
    catch(Exception e) { return "USER_NOT_FOUND"; }

    if(user.getToken() == token){

                 user.setDef(1);
                 return user.toString();    

    }

    return "USER_NOT_VALID";

}

最佳答案

返回用户的函数

public User returnUser() throws UserNotFoundException {

    try{
         return user = userList.get(user_id);
    }
    catch (Exception e) {
        throw new UserNotFoundException ("user " + user + " not found");
    }
}

主要方法

public static void main(String... args){

    try {
        System.out.println ("This will run always");

 // this will not work because returnUser() is not a static method and there is no "this" in "static void main()"
        User user = this.returnUser();

        System.out.println ("this should only run if a user was returned");
        return "Success";

    } catch (UserNotFoundException e) {
        System.out.pring("otherwise 'USER_NOT_FOUND' should be returned and end app.");
    }

异常类

class AppException extends Exception {
    public AppException(String msg) {
         super(msg);
    }
}

class UserNotFoundException extends AppException {
    public UserNotFoundException(String msg) {
         super(msg);
    }
}

UPD

这就是我所说的数据服务,代码是可编译的

import java.util.ArrayList;
import java.util.List;

public class App {

    public static void main(String... args) {

        App app = new App();

        try {
            app.run();

        } catch (UserNotFoundException e) {
            System.out.println("'USER_NOT_FOUND'");
        } catch (TodoNotFoundException e) {
            System.out.println("'TODO_NOT_FOUND'");
        } catch (AppException e) {
            System.out.println("Some other application exception");
        }
    }

    DataService dataService = null;

    public void run() throws AppException {

        System.out.println("This will run always");

        prepareDataService();

        completeTodo(1, 2);

        System.out.println("this should only run if a user was returned");

    }

    void prepareDataService() {

        List<Todo> todoList = new ArrayList<Todo>();
        List<User> userList = new ArrayList<User>();

        dataService = new DataService(todoList, userList);
    }

    void completeTodo(int todoId, int userId) throws AppException {

        Todo todo = dataService.findTodo(todoId);
        User user = dataService.findUser(userId);

        user.doSomething(todo);
    }
}

class DataService {

    private List<Todo> todoList;
    private List<User> userList;

    public DataService(List<Todo> todoList, List<User> userList) {
        this.todoList = todoList;
        this.userList = userList;
    }

    public Todo findTodo(int todoId) throws TodoNotFoundException {
        Todo todo = null;

        // find todo here

        if (todo == null) {
            throw new TodoNotFoundException("todo " + todo + " not found");
        }
        return todo;
    }

    public User findUser(int userId) throws UserNotFoundException {
        User user = null;

        // find user here

        if (user == null) {
            throw new UserNotFoundException("user " + user + " not found");
        }
        return user;
    }
}

class Todo {
}

class User {

    public void doSomething(Todo todo) {
    };
}

class AppException extends Exception {
    public AppException(String msg) {
        super(msg);
    }
}

class TodoNotFoundException extends AppException {
    public TodoNotFoundException(String msg) {
        super(msg);
    }
}

class UserNotFoundException extends AppException {
    public UserNotFoundException(String msg) {
        super(msg);
    }
}

关于java - 删除重复的 try/catch 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16081499/

相关文章:

python - 我该如何使用这种方法来获得结果?

java - 安卓和Java : cross-platform properties loading

java - 字母数字字符串对应的击键

java - JLabel、流程布局。将 JLabel 居中?

android - 无法连接到我的网络服务

c# - 在c#中访问两个按钮之间的数据

java - 哪个类可以访问我的方法?

java - 我的 Play 服务是否应该始终是带有 promise 的异步调用?

android - 比较在 Android 中使用 SHA-1 生成的两个哈希字符串

python - 如何在python中使用web.py处理上传的csv文件