新建全局异常捕获类
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value=Exception.class)
@ResponseBody
public Map<String, Object> exceptionHandlerMy(HttpServletRequest httpServletRequest,Exception e) {
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", "500");
result.put("msg", "系统错误...:"+e.toString());
return result;
}
}
手动创建异常
@RestController
public class ExceptionController {
@RequestMapping(value = "/showError", method = RequestMethod.GET)
public String showError() {
throw new RuntimeException();
}
}
一直不生效
后来发现是扫包时路径不对问题,新增handler路径,或者可以直接改成com.example下所有的包 !终于解决了!
@ComponentScan(value = {"com.example.demo.controller","com.example.demo.handler"})
@SpringBootApplication
@EnableSwagger2
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}