gpt4 book ai didi

java - Spring项目中如何处理异常?

转载 作者:行者123 更新时间:2023-12-01 17:16:32 24 4
gpt4 key购买 nike

正在写我的第一次战斗Spring-MVC项目。客户类(class)中有一个钱包(double钱包字段)。客户有机会从账户中提取资金。如果用户尝试提取的资金多于帐户可用的资金,我想在该方法中抛出错误。如何做到这一点?

我怎样才能摆脱if else构造并处理没有它们的方法 try catch 。或者用 if 更好?

客户服务:

package com.tinychiefdelights.service;

import com.tinychiefdelights.model.Customer;
import com.tinychiefdelights.repository.CustomerRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CustomerService extends UserService {


private CustomerRepository customerRepository;


@Autowired
public void setCustomerRepository(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}



// Методы
//

public void withdrawMoney(Customer customer, double money){
if (money <= customer.getWallet()) { // We make sure that the amount indicated by the customer is less than the wallet
customer.setWallet(customer.getWallet() - money);
} else {
//////////!!!! OR TRY CATCH and how to implement?!!!!!!!!
}
}

}

最佳答案

创建您的自定义异常类,例如OverWithDrawException注册一个 Spring Controller 来处理带有 HTTP 状态码的异常

@Controller
public class ExceptionHandlingController {

// @RequestHandler methods
...

// Exception handling methods

// Convert a predefined exception to an HTTP Status code
@ResponseStatus(value=HttpStatus.CONFLICT,
reason="Account over with draw attempt") // 409
@ExceptionHandler(OverWithDrawException.class)
public void overWithDrawHandle() {
// Nothing to do
}

@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
logger.error("Request: " + req.getRequestURL() + " raised " + ex);

ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}

// Specify name of a specific view that will be used to display the error:
@ExceptionHandler({SQLException.class,DataAccessException.class})
public String databaseError() {
// Nothing to do. Returns the logical view name of an error page, passed
// to the view-resolver(s) in usual way.
// Note that the exception is NOT available to this view (it is not added
// to the model) but see "Extending ExceptionHandlerExceptionResolver"
// below.
return "databaseError";
}

}

https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc 复制上述示例我很确定会有更新更好的方法来做到这一点。

关于java - Spring项目中如何处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61375311/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com