瑞吉外卖技术总结——异常处理

1.问题

        当新建员工时,由于用户名uername是不可重复的,所以新建员工时我们使用了数据库中存在的username时,系统会出现异常,我们需要因此编写异常处理。

2.方法

        方法一:我们可以使用try catch方法进行异常处理。

try{
    employeeService.addMember(employee);
}catch(Exception e){
    R.error("失败");
}

        方法二:新建一个全局异常处理器。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/*
* 全局异常处理
* */

//这里anntations利用注解指定处理的范围(使用RestController、controller注解的类里的所有函数都会进行异常处理)
@ControllerAdvice(annotations = {RestController.class, Controller.class})
//使用@ResponseBody将结果封装成JSON数据返回
@ResponseBody
//日志打印
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException exception){
        log.error(exception.getMessage());
        return R.error("失败了");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值