编写异常处理类
@ControllerAdvice //不指定包默认加了@Controller和@RestController都能控制
public class MyControllerAdvice {
/**
* 全局异常处理,反正异常返回统一格式的map
* @param ex
* @return
*/
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map<String,Object> exceptionHandler(Exception ex){
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",1001);
map.put("mag",ex.getMessage());
//发生异常进行日志记录,写入数据库或者其他处理,此处省略
return map;
}
}
加入启动扫描
@Configuration
@EnableAutoConfiguration
@ComponentScan({"com.suoron.springboot.controller","com.suoron.springboot.config"})
@ComponentScan({"com.suoron.springboot.service.impl"})
@ComponentScan({"com.suoron.springboot.exception"})
@MapperScan(basePackages = "com.suoron.springboot.dao.mapping")
@ImportResource("classpath:mybatis-tx.xml")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class,args);
}
}
网友评论